如何使用gRPC服务创建一个CRUD而不需要多次重复?

时间:2016-09-13 16:08:05

标签: protocol-buffers grpc

我正在尝试使用gRPC构建一个简单的CRUD服务,但我一直在发现自己创建的重叠消息。

最好用一个例子来描述:

message Todo {
  // id is only available for a persisted entity in database.
  string id = 1;
  string content = 2;
  // this is only available for users with admin role.
  string secret_content = 3;
}

service Todos {
  rpc CreateTodo(CreateRequest) returns (CreateResponse) {}
  rpc ReadTodo(ReadRequest) returns (ReadResponse) {}
}

message CreateRequest {
  // this todo is not supposed to have id,
  // should I create another version of Todo without an id field?
  Todo todo
}

message CreateResponse {
  // this todo will always have an id.
  Todo todo = 1;
}

message ReadRequest {
  string id = 1;
}

message ReadResponse {
  // this todo should only have the secret_content field if the
  // user is authenticated as an admin, if not, the field should not
  // fallback to the zero value, the whole field must be missing. 
  Todo todo = 1;
}

这是使用gRPC构建类似CRUD资源的好方法吗?也就是说,只有一条消息(Todo)表示资源,并将此消息包装在每个操作的响应/请求类型中。

Todo类型的消息是否包含所有请求/响应所涵盖的所有字段,而不是设置每个请求/响应未使用的字段?

1 个答案:

答案 0 :(得分:1)

  

Todo类型的消息是否包含所有请求/响应所涵盖的所有字段,而不是设置每个请求/响应未使用的字段?

是的,这似乎是一个合理的设计。在protobuf v2中,您可以标记此类字段optional,以便更容易理解。但是在v3中,默认情况下所有字段都是可选的。