简体   繁体   中英

Returning a list of messages

Given that i have multiple models, each needed to have their own create/get/get list API. Do i need to add two different types of messages (single and list) for every model?
For example : If i have a student type -

message Student{
    string name = 1;
}

and a rpc:

rpc CreateStudent(Student) returns (google.protobuf.Empty){
         ..............    
}

If i'd like to add a rpc to create a list of students, or get a list of students

rpc CreateStudends(??????) returns (google.protobuf.Empty){
             ..............    
}

rpc GetAllStudents() returns (??????){
         ..............    
}

Do i need to also define

message StudentList{
   repeated Student students = 1;
}

Or is there a way to use a list type directly in the message input/output?

Yes, basically - you would want a different message type per element type, or maybe a single root type with a oneof style content. Raw protobuf does not include a concept of generics or templates.

Some libraries do, but: that's outside of the specification.

You can simply add the stream keyword to your RPCs. No need to define a message field as repeated, stream will send or receive multiple independent messages.

message Student {
    string name = 1;
}

with RPCs:

rpc CreateStudent(Student) returns (google.protobuf.Empty) {
         ..............    
}

rpc CreateStudents(stream Student) returns (google.protobuf.Empty) {
             ..............    
}

rpc GetAllStudents() returns (stream Student) {
         ..............    
}

It's good practice to send/stream a response object rather than empty. Otherwise, you only have the gRPC response code to indicate a problem and will need to reference the logs to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM