英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论