在gqlgen的GraphQL模型中无法使用UUID作为ID类型的求助
问题描述
我尝试在Go模型中使用github.com/gofrs/uuid的UUID类型作为GraphQL的ID字段,不想通过string类型手动转换。当前代码如下:
Go模型:
package model import "github.com/gofrs/uuid" type Category struct { ID uuid.UUID `json:"id"` Name string `json:"name"` Description string `json:"description"` Picture string `json:"picture,omitempty"` }
GraphQL Schema:
# GraphQL Schema ... type Category { id: ID! name: String! description: String! picture: String }
gqlgen配置文件:
autobind: - <module-id>/path/to/model ... models: ID: model: - github.com/99designs/gqlgen/graphql.ID - github.com/gofrs/uuid.UUID Int: model: - github.com/99designs/gqlgen/graphql.Int - github.com/99designs/gqlgen/graphql.Int32 - github.com/99designs/gqlgen/graphql.Int64 ... schema: - graph/*.graphql struct_tag: json
运行后出现错误:
validation failed: packages.Load: /path/to/application/graph/prelude.generated.go:2177:17: ec.unmarshalInputID undefined (type *executionContext has no field or method unmarshalInputID) /path/to/application/graph/prelude.generated.go:2182:12: ec._ID undefined (type *executionContext has no field or method _ID) exit status 1 graph/resolver.go:3: running "go": exit status 1
请问有没有办法无需手动转换为string,原生将UUID用作ID?
更新
我已为此提交了一个拉取请求,希望能让更多UUID用户受益。
解决方案
要让gqlgen原生支持github.com/gofrs/uuid.UUID作为GraphQL的ID类型,需要调整配置优先级并确保类型映射正确:
调整ID类型的模型顺序
将github.com/gofrs/uuid.UUID放在ID模型列表的首位,让gqlgen优先使用该类型生成代码:models: ID: model: - github.com/gofrs/uuid.UUID - github.com/99designs/gqlgen/graphql.ID Int: model: - github.com/99designs/gqlgen/graphql.Int - github.com/99designs/gqlgen/graphql.Int32 - github.com/99designs/gqlgen/graphql.Int64确认autobind路径正确
替换配置中<module-id>为你的实际Go模块ID(如github.com/your-username/your-project),确保gqlgen能正确识别你的model包:autobind: - github.com/your-username/your-project/path/to/model依赖UUID的原生方法完成转换
github.com/gofrs/uuid.UUID已实现String()方法,gqlgen会自动利用该方法完成与GraphQLID类型的序列化/反序列化,无需手动编写转换逻辑。
完成配置调整后,重新运行gqlgen generate即可正常生成代码,原生使用UUID作为ID字段。
内容的提问来源于stack exchange,提问作者user4695271
相关产品推荐
相关产品推荐

