Generating a gRPC Service

    ent/schema/user.go

    Now re-run code-generation:

    1. go generate ./...

    First, entproto added a service definition to entpb.proto:

    ent/proto/entpb/entpb.proto

    1. service UserService {
    2. rpc Create ( CreateUserRequest ) returns ( User );
    3. rpc Get ( GetUserRequest ) returns ( User );
    4. rpc Update ( UpdateUserRequest ) returns ( User );
    5. rpc List ( ListUserRequest ) returns ( ListUserResponse );
    6. }

    ent/proto/entpb/entpb_grpc.pb.go

    The second file, entpub_user_service.go contains a generated implementation for this interface. For example, an implementation for the Get method:

    1. // Get implements UserServiceServer.Get
    2. func (svc *UserService) Get(ctx context.Context, req *GetUserRequest) (*User, error) {
    3. var (
    4. err error
    5. get *ent.User
    6. )
    7. id := int(req.GetId())
    8. switch req.GetView() {
    9. get, err = svc.client.User.Get(ctx, id)
    10. case GetUserRequest_WITH_EDGE_IDS:
    11. Where(user.ID(id)).
    12. Only(ctx)
    13. default:
    14. return nil, status.Error(codes.InvalidArgument, "invalid argument: unknown view")
    15. }
    16. switch {
    17. case err == nil:
    18. return toProtoUser(get)
    19. case ent.IsNotFound(err):
    20. return nil, status.Errorf(codes.NotFound, "not found: %s", err)
    21. default:
    22. return nil, status.Errorf(codes.Internal, "internal error: %s", err)

    Not bad! Next, let’s create a gRPC server that can serve requests to our service.