Search code examples
javaspring-bootgraphqlgraphql-java

How to add username to graphql context/data fetching environment from RestController


I have a spring rest controller with a single endpoint to receive all graphql query/mutation requests. the endpoint looks as below

@RequestMapping(value="/test", method = RequestMethod.POST)
public ResponseEntity testService(@RequestHeader("user") String userName, 
@RequestBody String query) {
ExecutionResult result = graphQL.execute(query);
}

I have properly set up my graphql object. How can I pass username from request header to graphql query so data fetcher can retrieve it to update userModified info?


Solution

  • Don't use the simple GraphQL#execute(String) method, but the more powerful version GraphQL#execute(ExecutionInput).

    E.g.

    ExecutionResult executionResult = graphQL.execute(ExecutionInput.newExecutionInput()
                    .query(query)
                    .context(username)
                    .build());