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

谢谢,

推荐答案

我认为您可以在父解析器的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)
    // ...
}

字段Argsmap[string]interface{},因此您可以通过名称访问参数,然后键入-断言它们应该是什么.

如果这不起作用,也可以try graphql.GetOperationContext,这基本上是没有记录的……(归功于@Shashank Sachan)

graphql.GetOperationContext(ctx).Variables["device"].(string)

Go相关问答推荐

如何将泛型函数作为参数传递给golang中的另一个函数?

Term~T中的类型不能是类型参数,但可以是引用类型参数的切片

Go在使用HTTP代理时如何处理DNS请求?

Golang Viper:如果第一个字段不存在,如何从另一个字段获取值

有没有办法通过Go cmdline或IDE(IntelliJ)找出我的 struct 实现了什么接口?

重新赋值变量时未清除动态类型-这是错误吗?

从MySQL/GO表获取行数据

Cypher 查找(多个)最低 node

如何绕过深层 xml,没有嵌套循环?

是否可以使用标准库构建 Go 二进制文件?

这是泛型的有效用例吗?

Go 中的 YAML 自定义标签

对 CSV 进行单元测试失败

当客户端同时是服务器时,需要什么 mTLS 证书?

获取 nil 指针类型的 reflect.Value

致命错误 - 所有 Goroutines 都睡着了!僵局

Golang - 客户 Unmarshaler/Marshaler 在指针上具有 nil/null 值

Golang 与 Cassandra db 使用 docker-compose:cannot connect (gocql)

并发 map map导致的 Golang 数据竞争

是否可以动态加载 Go 代码?