跳到主要内容

配置服务方法生成选项

默认情况下,entproto 会为使用 ent.Service() 注解的 ent.Schema 生成多个服务方法。通过在 entproto.Service() 注解中包含参数 entproto.Methods(),可以自定义方法生成。entproto.Methods() 接受位标志来确定应生成哪些服务方法。可用标志包括:

// 为 entproto.Service 生成 Create gRPC 服务方法
entproto.MethodCreate

// 为 entproto.Service 生成 Get gRPC 服务方法
entproto.MethodGet

// 为 entproto.Service 生成 Update gRPC 服务方法
entproto.MethodUpdate

// 为 entproto.Service 生成 Delete gRPC 服务方法
entproto.MethodDelete

// 为 entproto.Service 生成 List gRPC 服务方法
entproto.MethodList

// 为 entproto.Service 生成 BatchCreate gRPC 服务方法
entproto.MethodBatchCreate

// 为 entproto.Service 生成所有服务方法
// 此行为与不包含 entproto.Methods 时相同
entproto.MethodAll

要生成包含多个方法的服务,可使用位或运算组合标志。

要通过实际示例查看效果,我们可以修改 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 方法。完美!