14

in my proto file, I define a service interface:

syntax = "proto3";

package mynamespace;

import "google/protobuf/empty.proto";

service MyService {
    rpc isTokenValid (TokenRequest) returns (TokenResponse) {
    }
}

message TokenRequest {
    string token = 1;
}

message TokenResponse {
    bool valid = 1;
}

The above works well, however, I think the TokenResponse is ugly. the bool valid = 1 is redundant, ideally it should be like the following

rpc isTokenValid (TokenRequest) returns (BooleanResponse) {
}

But I didn't figure out how to write proto file like that, can any expert share some best practice on that?

Thanks in advance!

Updates:

How to return an array directly? For example, this is my code:

service MyService {
    rpc arrayResponse (TokenRequest) returns (ArrayResponse) {}
}

message ArrayResponse {
    repeated Data data = 1;
}

message Data {
    string field1 = 1;
    string field2 = 2;
}

I think this is ugly, how to refactor in the correct google way?

Thanks!

Jeff Tian
  • 5,210
  • 3
  • 51
  • 71

1 Answers1

26

Why not just use the predefined BoolValue as specified in Google's wrappers.proto for your response?

Something like:

syntax = "proto3";

package mynamespace;

import "google/protobuf/wrappers.proto";

service MyService {
    rpc isTokenValid (TokenRequest) returns (google.protobuf.BoolValue) {
    }
}

message TokenRequest {
    string token = 1;
}
Michael Krause
  • 4,689
  • 1
  • 21
  • 25
  • Thank you very much! Do you know how to return an array response directly? Can you check my updated question? – Jeff Tian Jan 10 '19 at 07:00
  • I think the way you proposed (ArrayResponse with a repeated field) is correct. Did you want this to be able to return an array of arbitrary type? If so, you could use google.protobuf.Any as the data type. – Michael Krause Jan 10 '19 at 20:21
  • Thank you! I want to return an typed array without wrap it inside an extra data field. Only Any can do it? – Jeff Tian Jan 11 '19 at 02:12
  • 3
    WARNING: That is a dangerous path for compatibility. You never know what requests come in the future. you can no longer add more fields into your response. Every request and every response should be 'your' message object so that is flexible and future proof. this is also why gRPC only allows 1 request and 1 response. – Dean Hiller May 01 '20 at 12:08
  • @DeanHiller Agreed. In reality, a proper service definition would utilize request and response messages that the service creator would author. These authored messages could then make use of the google wrapper classes as field values in cases where you need nullable primitive values. – Michael Krause May 01 '20 at 17:41