1 回答

TA贡献1827条经验 获得超8个赞
FieldContext我认为您可以在父解析器中找到参数。graphql.GetFieldContext你可以这样得到它:
// Version is the resolver for the version field.
func (r *mainResolver) Version(ctx context.Context, obj *models.Main) (*models.Version, error) {
device := graphql.GetFieldContext(ctx).Parent.Args["device"].(string)
// ...
}
该字段Args是一个map[string]interface{},因此您可以按名称访问参数,然后将它们键入断言为它们应该是什么。
如果解析器嵌套了多个级别,您可以编写一个函数沿着上下文链向上遍历,直到找到具有该值的祖先。使用 Go 1.18+ 泛型,该函数可以重用于任何值类型,使用类似于 json.Unmarshal 的模式:
func FindGqlArgument[T any](ctx context.Context, key string, dst *T) {
if dst == nil {
panic("nil destination value")
}
for fc := graphql.GetFieldContext(ctx); fc != nil; fc = fc.Parent {
v, ok := fc.Args[key]
if ok {
*dst = v.(T)
}
}
// optionally handle failure state here
}
并将其用作:
func (r *deeplyNestedResolver) Version(ctx context.Context, obj *models.Main) (*models.Version, error) {
var device string
FindGqlArgument(ctx, "device", &device)
}
如果这不起作用,也可以尝试 with graphql.GetOperationContext,这基本上没有记录......(归功于@Shashank Sachan)
graphql.GetOperationContext(ctx).Variables["device"].(string)
- 1 回答
- 0 关注
- 108 浏览
添加回答
举报