为了账号安全,请及时绑定邮箱和手机立即绑定

GqlGen - 在字段解析器中访问查询输入参数

GqlGen - 在字段解析器中访问查询输入参数

Go
慕盖茨4494581 2023-02-21 13:20:55
使用 GqlGen 生成代码后,已经创建了一些字段解析器方法。我需要访问字段解析器中的查询输入参数,但我不确定如何访问它。我需要从上下文中获取这些值吗?或者还有其他办法吗?查询解析器:func (r *queryResolver) Main(ctx context.Context, device string) (*models.Main, error) {...}字段解析器:// Version is the resolver for the version field.func (r *mainResolver) Version(ctx context.Context, obj *models.Main) (*models.Version, error) {        // I NEED TO ACCESS device param here which is passed in Main method    panic(fmt.Errorf("not implemented: Version - version"))}谢谢,
查看完整描述

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)


查看完整回答
反对 回复 2023-02-21
  • 1 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号