跳到主要内容

配置服务方法生成

默认情况下 entproto 会根据 ent.Service()ent.Schema 注解生成一系列服务方法。 方法生成可以在 entproto.Service() 注解中包含 entproto.Methods() 参数进行自定义。 entproto.Methods() 接收位(bit)标志来决定哪个方法会被生成。这些标志包括:

// Generates a Create gRPC service method for the entproto.Service.
entproto.MethodCreate

// Generates a Get gRPC service method for the entproto.Service.
entproto.MethodGet

// Generates an Update gRPC service method for the entproto.Service.
entproto.MethodUpdate

// Generates a Delete gRPC service method for the entproto.Service.
entproto.MethodDelete

// Generates a List gRPC service method for the entproto.Service.
entproto.MethodList

// Generates a Batch Create gRPC service method for the entproto.Service.
entproto.MethodBatchCreate

// Generates all service methods for the entproto.Service.
// This is the same behavior as not including entproto.Methods.
entproto.MethodAll

若要生成服务的多个方法,使用 OR(或) 对标志进行运算。

要查看实际效果,我们可以修改我们的 ent 模式。假设我们希望阻止 gRPC 客户端修改实体。 我们可以通过修改 ent/schema/user.go 实现:

ent/schema/user.go
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entproto.Message(),
entproto.Service(
entproto.Methods(entproto.MethodCreate | entproto.MethodGet | entproto.MethodList | entproto.MethodBatchCreate),
),
}
}

重新运行 go generate ./... 会生成 entpb.proto 中定义的服务:

ent/proto/entpb/entpb.proto
service UserService {
rpc Create ( CreateUserRequest ) returns ( User );

rpc Get ( GetUserRequest ) returns ( User );

rpc List ( ListUserRequest ) returns ( ListUserResponse );

rpc BatchCreate ( BatchCreateUsersRequest ) returns ( BatchCreateUsersResponse );
}

请注意服务不再包含 UpdateDelete 方法了。完美!