如何在Go中解析GraphQL查询以获取操作名称?

huangapple go评论66阅读模式
英文:

How can I parse graphql query to get operation name in go?

问题

我正在使用这个Go库来解析GraphQL查询字符串:github.com/graphql-go/graphql/language/parser

我有以下代码:

query := "subscription event {event(on: \"xxxx\") {msg    __typename  }}"
p, err := parser.Parse(parser.ParseParams{Source: query})

返回的p是一个*ast.Document实例。p有一个Definitions字段,它是一个ast.Node[]数组。

但是我不知道如何从查询中获取操作名称。在这种情况下,操作名称应该是subscription

英文:

I am using this go library to parse graphql query string: github.com/graphql-go/graphql/language/parser.

I have below code:

query := "subscription event {event(on: "xxxx") {msg    __typename  }}"
p, err := parser.Parse(parser.ParseParams{Source: query})

the returned p is an instance of *ast.Document. p has a Definitions field which is a ast.Node[] array.

But what I don't know is how to get the operation name from the query. In this case, it should be subscription.

答案1

得分: 0

由于p.Definitions是一个Node切片,而Node是由ast.OperationDefinition实现的接口。

因此,为了提取OperationDefinition节点的数据,你需要进行断言。

for _, d := range p.Definitions {
    if oper, ok := d.(*ast.OperationDefinition); ok {
        fmt.Println(oper.Operation)
    }
}

这段代码可以遍历p.Definitions切片,并通过断言将每个元素转换为ast.OperationDefinition类型。如果转换成功,就可以访问oper.Operation属性,该属性表示操作类型(如查询、变更等)。

英文:

Since p.Definitions are slice of Node that is an interface that is implemented by ast.OperationDefinition.

So in order to extract the data of OperationDefinition node, you need to perform an assertion.

for _, d := range p.Definitions {
    if oper, ok := d.(*ast.OperationDefinition); ok {
        fmt.Println(oper.Operation)
	}
}

huangapple
  • 本文由 发表于 2023年1月13日 15:07:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75105875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定