doc/md: various improvements to gRPC tutorial (#2977)

This commit is contained in:
Dan Kortschak
2022-09-30 15:29:53 +09:30
committed by GitHub
parent 837d077f98
commit 7d3d898f60
6 changed files with 51 additions and 56 deletions

View File

@@ -5,7 +5,7 @@ sidebar_label: Generating a Service
---
Generating Protobuf structs generated from our `ent.Schema` can be useful, but what we're really interested in is getting an actual server that can create, read, update, and delete entities from an actual database. To do that, we need to update just one line of code! When we annotate a schema with `entproto.Service`, we tell the `entproto` code-gen that we are interested in generating a gRPC service definition, from the `protoc-gen-entgrpc` will read our definition and generate a service implementation. Edit `ent/schema/user.go` and modify the schema's `Annotations`:
```go {4}
```go title="ent/schema/user.go" {4}
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entproto.Message(),
@@ -33,7 +33,7 @@ ent/proto/entpb
First, `entproto` added a service definition to `entpb.proto`:
```protobuf
```protobuf title="ent/proto/entpb/entpb.proto"
service UserService {
rpc Create ( CreateUserRequest ) returns ( User );
@@ -51,7 +51,7 @@ service UserService {
In addition, two new files were created. The first, `entpb_grpc.pb.go`, contains the gRPC client stub and the interface definition. If you open the file, you will find in it (among many other things):
```go
```go title="ent/proto/entpb/entpb_grpc.pb.go"
// UserServiceClient is the client API for UserService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please
@@ -68,26 +68,27 @@ type UserServiceClient interface {
The second file, `entpub_user_service.go` contains a generated implementation for this interface. For example, an implementation for the `Get` method:
```go
```go title="ent/proto/entpb/entpb_user_service.go"
// Get implements UserServiceServer.Get
func (svc *UserService) Get(ctx context.Context, req *GetUserRequest) (*User, error) {
var (
err error
get *ent.User
)
id := int(req.GetId())
switch req.GetView() {
case GetUserRequest_VIEW_UNSPECIFIED, GetUserRequest_BASIC:
get, err = svc.client.User.Get(ctx, int(req.GetId()))
get, err = svc.client.User.Get(ctx, id)
case GetUserRequest_WITH_EDGE_IDS:
get, err = svc.client.User.Query().
Where(user.ID(int(req.GetId()))).
Where(user.ID(id)).
Only(ctx)
default:
return nil, status.Errorf(codes.InvalidArgument, "invalid argument: unknown view")
return nil, status.Error(codes.InvalidArgument, "invalid argument: unknown view")
}
switch {
case err == nil:
return toProtoUser(get), nil
return toProtoUser(get)
case ent.IsNotFound(err):
return nil, status.Errorf(codes.NotFound, "not found: %s", err)
default: