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

Time:01-17

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.

CodePudding user response:

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)
    }
}
  • Related