Skip to content

Commit 1bbaeea

Browse files
committed
Allow DataFetcherResult to set extension values during execution
1 parent 7f0e4de commit 1bbaeea

4 files changed

Lines changed: 124 additions & 14 deletions

File tree

‎src/main/java/graphql/execution/DataFetcherResult.java‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import java.util.ArrayList;
1111
import java.util.List;
12+
import java.util.Map;
1213
import java.util.function.Consumer;
1314

1415
import static graphql.Assert.assertNotNull;
@@ -18,7 +19,7 @@
1819
* An object that can be returned from a {@link DataFetcher} that contains both data, local context and errors to be relativized and
1920
* added to the final result. This is a useful when your ``DataFetcher`` retrieves data from multiple sources
2021
* or from another GraphQL resource or you want to pass extra context to lower levels.
21-
*
22+
* <p>
2223
* This also allows you to pass down new local context objects between parent and child fields. If you return a
2324
* {@link #getLocalContext()} value then it will be passed down into any child fields via
2425
* {@link graphql.schema.DataFetchingEnvironment#getLocalContext()}
@@ -31,6 +32,7 @@ public class DataFetcherResult<T> {
3132
private final T data;
3233
private final List<GraphQLError> errors;
3334
private final Object localContext;
35+
private final Map<Object, Object> extensions;
3436

3537
/**
3638
* Creates a data fetcher result
@@ -44,13 +46,14 @@ public class DataFetcherResult<T> {
4446
@Deprecated
4547
@DeprecatedAt("2019-01-11")
4648
public DataFetcherResult(T data, List<GraphQLError> errors) {
47-
this(data, errors, null);
49+
this(data, errors, null, null);
4850
}
4951

50-
private DataFetcherResult(T data, List<GraphQLError> errors, Object localContext) {
52+
private DataFetcherResult(T data, List<GraphQLError> errors, Object localContext, Map<Object, Object> extensions) {
5153
this.data = data;
5254
this.errors = ImmutableList.copyOf(assertNotNull(errors));
5355
this.localContext = localContext;
56+
this.extensions = extensions;
5457
}
5558

5659
/**
@@ -83,6 +86,22 @@ public Object getLocalContext() {
8386
return localContext;
8487
}
8588

89+
/**
90+
* A data fetcher result can supply extension values that will be merged into the result
91+
* via the {@link graphql.extensions.ExtensionsBuilder} at the end of the operation.
92+
* <p>
93+
* The {@link graphql.extensions.ExtensionsMerger} in place inside the {@link graphql.extensions.ExtensionsBuilder}
94+
* will control how these extension values get merged.
95+
*
96+
* @return a map of extension values to be merged
97+
*
98+
* @see graphql.extensions.ExtensionsBuilder
99+
* @see graphql.extensions.ExtensionsMerger
100+
*/
101+
public Map<Object, Object> getExtensions() {
102+
return extensions;
103+
}
104+
86105
/**
87106
* This helps you transform the current DataFetcherResult into another one by starting a builder with all
88107
* the current values and allows you to transform it how you want.
@@ -112,11 +131,13 @@ public static class Builder<T> {
112131
private T data;
113132
private Object localContext;
114133
private final List<GraphQLError> errors = new ArrayList<>();
134+
private Map<Object, Object> extensions;
115135

116136
public Builder(DataFetcherResult<T> existing) {
117137
data = existing.getData();
118138
localContext = existing.getLocalContext();
119139
errors.addAll(existing.getErrors());
140+
extensions = existing.extensions;
120141
}
121142

122143
public Builder(T data) {
@@ -158,8 +179,13 @@ public Builder<T> localContext(Object localContext) {
158179
return this;
159180
}
160181

182+
public Builder<T> extensions(Map<Object, Object> extensions) {
183+
this.extensions = extensions;
184+
return this;
185+
}
186+
161187
public DataFetcherResult<T> build() {
162-
return new DataFetcherResult<>(data, errors, localContext);
188+
return new DataFetcherResult<>(data, errors, localContext, extensions);
163189
}
164190
}
165191
}

‎src/main/java/graphql/execution/ExecutionStrategy.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters;
1919
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
2020
import graphql.execution.instrumentation.parameters.InstrumentationFieldParameters;
21+
import graphql.extensions.ExtensionsBuilder;
2122
import graphql.introspection.Introspection;
2223
import graphql.language.Argument;
2324
import graphql.language.Field;
@@ -330,6 +331,7 @@ protected FetchedValue unboxPossibleDataFetcherResult(ExecutionContext execution
330331
if (result instanceof DataFetcherResult) {
331332
DataFetcherResult<?> dataFetcherResult = (DataFetcherResult<?>) result;
332333
executionContext.addErrors(dataFetcherResult.getErrors());
334+
addExtensionsIfPresent(executionContext,dataFetcherResult);
333335

334336
Object localContext = dataFetcherResult.getLocalContext();
335337
if (localContext == null) {
@@ -351,6 +353,16 @@ protected FetchedValue unboxPossibleDataFetcherResult(ExecutionContext execution
351353
}
352354
}
353355

356+
private void addExtensionsIfPresent(ExecutionContext executionContext, DataFetcherResult<?> dataFetcherResult) {
357+
Map<Object, Object> extensions = dataFetcherResult.getExtensions();
358+
if (extensions != null) {
359+
ExtensionsBuilder extensionsBuilder = executionContext.getGraphQLContext().get(ExtensionsBuilder.class);
360+
if (extensionsBuilder != null) {
361+
extensionsBuilder.addValues(extensions);
362+
}
363+
}
364+
}
365+
354366
protected <T> CompletableFuture<T> handleFetchingException(ExecutionContext executionContext,
355367
DataFetchingEnvironment environment,
356368
Throwable e) {

‎src/test/groovy/graphql/execution/DataFetcherResultTest.groovy‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,43 @@ class DataFetcherResultTest extends Specification {
5555
!result.hasErrors()
5656
}
5757

58-
def "transforming"() {
58+
def "can set extensions"() {
59+
60+
when:
61+
def dfr = DataFetcherResult.newResult()
62+
.extensions([x: "y"]).build()
63+
64+
then:
65+
dfr.getExtensions() == [x : "y"]
66+
67+
when:
68+
dfr = DataFetcherResult.newResult()
69+
.data("x")
70+
.build()
71+
72+
then:
73+
dfr.getExtensions() == null
74+
75+
}
76+
77+
def "transforming works"() {
5978
when:
6079
def original = DataFetcherResult.newResult().data("hello")
61-
.errors([error1]).localContext("world").build()
80+
.errors([error1]).localContext("world")
81+
.extensions([x: "y"]).build()
6282
def result = original.transform({ builder -> builder.error(error2) })
6383
then:
6484
result.getData() == "hello"
6585
result.getLocalContext() == "world"
86+
result.getExtensions() == [x : "y"]
87+
result.getErrors() == [error1, error2]
88+
89+
when:
90+
result = result.transform({ builder -> builder.extensions(a : "b") })
91+
then:
92+
result.getData() == "hello"
93+
result.getLocalContext() == "world"
94+
result.getExtensions() == [a : "b"]
6695
result.getErrors() == [error1, error2]
6796
}
6897
}

‎src/test/groovy/graphql/extensions/ExtensionsBuilderTest.groovy‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package graphql.extensions
22

3-
import graphql.ExecutionInput
43
import graphql.ExecutionResult
54
import graphql.TestUtil
5+
import graphql.execution.DataFetcherResult
66
import graphql.schema.DataFetcher
77
import graphql.schema.DataFetchingEnvironment
88
import graphql.schema.GraphQLTypeUtil
99
import org.jetbrains.annotations.NotNull
1010
import spock.lang.Specification
1111

12+
import static graphql.ExecutionInput.newExecutionInput
1213
import static graphql.extensions.ExtensionsBuilder.newExtensionsBuilder
1314
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring
1415
import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring
@@ -122,11 +123,12 @@ class ExtensionsBuilderTest extends Specification {
122123
"""
123124

124125
def extensionsBuilder = newExtensionsBuilder()
125-
extensionsBuilder.addValue("added","explicitly")
126+
extensionsBuilder.addValue("added", "explicitly")
126127

127-
def ei = ExecutionInput.newExecutionInput("query q { name street id }")
128+
def ei = newExecutionInput("query q { name street id }")
128129
.graphQLContext({ ctx ->
129-
ctx.put(ExtensionsBuilder.class, extensionsBuilder) })
130+
ctx.put(ExtensionsBuilder.class, extensionsBuilder)
131+
})
130132
.build()
131133

132134

@@ -144,12 +146,53 @@ class ExtensionsBuilderTest extends Specification {
144146
er.errors.isEmpty()
145147
er.extensions == [
146148
"added": "explicitly",
147-
common: [
149+
common : [
148150
name : "String!",
149151
street: "String",
150152
id : "ID!",
151153
],
152154
// we break them out so we have common and not common entries
155+
name : "String!",
156+
street : "String",
157+
id : "ID!",
158+
]
159+
}
160+
161+
162+
def "integration test that shows it working when they use DataFetcherResult and defaulted values"() {
163+
def sdl = """
164+
type Query {
165+
name : String!
166+
street : String
167+
id : ID!
168+
}
169+
"""
170+
171+
DataFetcher dfrDF = new DataFetcher() {
172+
@Override
173+
Object get(DataFetchingEnvironment env) throws Exception {
174+
def fieldMap = [:]
175+
fieldMap.put(env.getFieldDefinition().name, GraphQLTypeUtil.simplePrint(env.getFieldDefinition().type))
176+
return DataFetcherResult.newResult().data("ignored").extensions(fieldMap).build()
177+
}
178+
}
179+
180+
def graphQL = TestUtil.graphQL(sdl, newRuntimeWiring()
181+
.type(newTypeWiring("Query").dataFetchers([
182+
name : dfrDF,
183+
street: dfrDF,
184+
id : dfrDF,
185+
])))
186+
.build()
187+
188+
when:
189+
def ei = newExecutionInput("query q { name street id }")
190+
.build()
191+
192+
def er = graphQL.execute(ei)
193+
then:
194+
er.errors.isEmpty()
195+
er.extensions == [
153196
name : "String!",
154197
street: "String",
155198
id : "ID!",
@@ -165,7 +208,7 @@ class ExtensionsBuilderTest extends Specification {
165208
}
166209
"""
167210

168-
def ei = ExecutionInput.newExecutionInput("query q { name street id }")
211+
def ei = newExecutionInput("query q { name street id }")
169212
.build()
170213

171214

@@ -203,8 +246,8 @@ class ExtensionsBuilderTest extends Specification {
203246
}
204247
"""
205248

206-
def ei = ExecutionInput.newExecutionInput("query q { name street id }")
207-
.root(["name" : "Brad", "id" :1234])
249+
def ei = newExecutionInput("query q { name street id }")
250+
.root(["name": "Brad", "id": 1234])
208251
.build()
209252

210253

0 commit comments

Comments
 (0)