How to return a simple boolean value in ProtoBuffer?
Asked Answered
P

1

17

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!

President answered 26/12, 2018 at 9:37 Comment(0)
D
30

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;
}
Deadman answered 9/1, 2019 at 3:5 Comment(5)
Thank you very much! Do you know how to return an array response directly? Can you check my updated question?President
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.Deadman
Thank you! I want to return an typed array without wrap it inside an extra data field. Only Any can do it?President
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.Winniewinnifred
@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.Deadman

© 2022 - 2024 — McMap. All rights reserved.