graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.87k stars 839 forks source link

Determine Operation type from Params.RequestString #562

Closed andrewzlchen closed 4 years ago

andrewzlchen commented 4 years ago

Hey guys,

I'm looking to make custom external behavior depending on the type of the incoming request (query vs. mutation vs. subscription), but I haven't found a solution besides manually parsing the request string to check whether the token mutation (or others) are contained in the string (which is probably slow and errorprone).

I looked a bit into the source and only found private methods that parse the request string into an AST before processing, which I cannot access.

Maybe I've missed it, but is there a way to be able to tell whether the incoming query is a query vs mutation before calling graphql.Do(p Params)?

For example

// queryRequestType should equal "query"
queryRequestType := graphql.GetOperationType(`
{
  testQuery {
    field1
    field2
  }
}
`)

// mutationRequestType should equal "mutation"
mutationRequestType  := graphql.GetOperationType(`
mutation {
  testMutation(input: {stuff: ""}) {
    field1
    field2
  }
}
`)

Any help is appreciated. Thanks!

andrewzlchen commented 4 years ago

Nevermind, I found the answer which was to use the parser subpackage like so

import (
    "github.com/graphql-go/graphql/language/parser"
    "github.com/graphql-go/graphql/language/source"
)

func getOperationTypeOfReq(reqStr string) string{
    source := source.NewSource(&source.Source{
        Body: []byte(requestStr),
        Name: "GraphQL request",
    })

    AST, err := parser.Parse(parser.ParseParams{Source: source})
    if err != nil {
        return ""
    }

    for _, node := range AST.Definitions {
        if operationDef, ok := node.(*ast.OperationDefinition); ok {
            return operationDef.Operation
        }
    }
    return ""
}