Search code examples
graphqlgraphql-java

How to reference Context object in provided class methods?


We are using graphql-java and with com.coxautodev.graphql.tools.SchemaParser (from graphql-java-tools) we are creating executable schema - and it works just fine. Now we need to add user information and propagate it to our graphql method logic. The obvious approach is to use "context" object.

So, in mutations.graphql file there is:

type Mutations
  createGroup(input: CreateGroupInput): IdRequest
  ...

On the other hand, there is a Java class with the corresponding method:

IdRequest createGroup(CreateGroupInput input) {
  ...
}

Then, when calling graphql.GraphQL.execute(myQuery, contextObject) how to read this contextObject into Java method above?


Solution

  • The thing I was looking for is DataFetchingEnvironment (see Fetching data).

    The "contextObject" can then be retrieved in Java class by adding DataFetchingEnvironment as a last argument, like:

    IdRequest createGroup(CreateGroupInput input, DataFetchingEnvironment environment) {
      Object contextObject = environment.getContext();
      ...
    }