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

ali*_*ali 6 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

jpa*_*jpa 2

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

是的,这看起来是一个合理的设计。在 protobuf v2 中,您可以标记这些字段optional以使其更易于理解。但在 v3 中,默认情况下所有字段都是可选的。