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

使用 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"))

}

谢谢,


慕盖茨4494581
浏览 110回答 1
1回答

斯蒂芬大帝

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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go