My responses from GraphQL have to follow a particular format of
{
data:{}
errors:[{}]
extensions:{}
}
However, I am uncertain how to respond with extensions from my methods. I am using graphql-spring-boot which pulls in graphql-java, graphql-java-tools, and graphql-java-servlet.
I understand that my results from a query/mutation method will be wrapped in the data object, and if any exceptions were thrown they'll be wrapped in errors.
If I have a GraphQL Schema defined as
type Query {
someQuery(input: String!) : String!
}
and a corresponding Java method
public String someQuery(String input) {
return "Hello, world!";
}
The GraphQL response will be
{
data: { "Hello, world!"}
}
I would like to know how I am able to add extensions to my GraphQL response so that the output is as:
{
data: {"Hello, world!"}
extensions: { <something>}
}
The best way I've found to return extensions is to implement a subclass of SimpleInstrumentation that overrides instrumentExecutionResult (code stolen partially from graphql-java's TracingInstrumentation):
@Override
public CompletableFuture<ExecutionResult> instrumentExecutionResult(
ExecutionResult executionResult,
InstrumentationExecutionParameters parameters) {
Map<Object, Object> currentExt = executionResult.getExtensions();
Map<Object, Object> newExtensionMap = new LinkedHashMap<>();
newExtensionMap.putAll(currentExt == null ? Collections.emptyMap() : currentExt);
newExtensionMap.put("MyExtensionKey", myExtensionValue);
return CompletableFuture.completedFuture(
new ExecutionResultImpl(
executionResult.getData(),
executionResult.getErrors(),
newExtensionMap));
}
When setting up the GraphQL instance you then pass an instance of the instrumentation class in:
GraphQL graphQL = GraphQL
.newGraphQL(schema)
.instrumentation(new MyInstrumentation())
.build()
(Not sure entirely how this is handled by graphql-spring-boot but would imagine there is some way to @Autowire or otherwise configure the GraphQL instance? InstrumentationProvider from graphql-java-servlet might be what you'd use to do this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With