Skip to content

Commit bbeed5b

Browse files
committed
report null @skip/@include if variables as field errors with location and path
1 parent 06a0410 commit bbeed5b

5 files changed

Lines changed: 227 additions & 24 deletions

File tree

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

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,11 +212,21 @@ private CompletableFuture<ExecutionResult> executeOperation(ExecutionContext exe
212212
.graphQLContext(graphQLContext)
213213
.build();
214214

215-
MergedSelectionSet fields = fieldCollector.collectFields(
216-
collectorParameters,
217-
operationDefinition.getSelectionSet(),
218-
executionContext.hasIncrementalSupport()
219-
);
215+
MergedSelectionSet fields;
216+
try {
217+
fields = fieldCollector.collectFields(
218+
collectorParameters,
219+
operationDefinition.getSelectionSet(),
220+
executionContext.hasIncrementalSupport()
221+
);
222+
} catch (NonNullableValueCoercedAsNullException e) {
223+
// a root level @skip / @include 'if' argument coerced to null - there is no enclosing field to null,
224+
// so this is reported the same way as any other variable coercion failure
225+
ExecutionResult executionResult = new ExecutionResultImpl(Collections.singletonList(e));
226+
executeOperationCtx.onDispatched();
227+
executeOperationCtx.onCompleted(executionResult, e);
228+
return completedFuture(executionResult);
229+
}
220230

221231
ResultPath path = ResultPath.rootPath();
222232
ExecutionStepInfo executionStepInfo = newExecutionStepInfo().type(operationRootType).path(path).build();

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import graphql.ExecutionResult;
77
import graphql.ExecutionResultImpl;
88
import graphql.GraphQLError;
9+
import graphql.GraphqlErrorBuilder;
910
import graphql.Internal;
1011
import graphql.PublicSpi;
1112
import graphql.SerializationError;
@@ -805,10 +806,26 @@ protected FieldValueInfo completeValue(ExecutionContext executionContext, Execut
805806
handleUnresolvedTypeProblem(executionContext, parameters, ex);
806807
// complete field as null, validating it is nullable
807808
return getFieldValueInfoForNull(parameters);
809+
} catch (NonNullableValueCoercedAsNullException ex) {
810+
// a @skip / @include 'if' argument in the sub selection coerced to null - this is a field error
811+
// on this field, so null it (propagating as usual) rather than failing the whole operation
812+
handleSubSelectionCoercionProblem(executionContext, parameters, ex);
813+
return getFieldValueInfoForNull(parameters);
808814
}
809815
return new FieldValueInfo(OBJECT, fieldValue);
810816
}
811817

818+
private void handleSubSelectionCoercionProblem(ExecutionContext context, ExecutionStrategyParameters parameters, NonNullableValueCoercedAsNullException e) {
819+
GraphQLError error = GraphqlErrorBuilder.newError()
820+
.message(e.getMessage())
821+
.locations(e.getLocations())
822+
.path(parameters.getPath())
823+
.errorType(e.getErrorType())
824+
.build();
825+
826+
addErrorToRightContext(error, parameters, context);
827+
}
828+
812829
private void handleUnresolvedTypeProblem(ExecutionContext context, ExecutionStrategyParameters parameters, UnresolvedTypeException e) {
813830
UnresolvedTypeError error = new UnresolvedTypeError(parameters.getPath(), parameters.getExecutionStepInfo(), e);
814831

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import graphql.PublicApi;
77
import graphql.language.SourceLocation;
88
import graphql.language.VariableDefinition;
9+
import graphql.language.VariableReference;
910
import graphql.schema.GraphQLArgument;
1011
import graphql.schema.GraphQLInputObjectField;
1112
import graphql.schema.GraphQLType;
@@ -72,6 +73,13 @@ public NonNullableValueCoercedAsNullException(GraphQLInputObjectField inputTypeF
7273
this.path = path;
7374
}
7475

76+
public NonNullableValueCoercedAsNullException(String directiveName, VariableReference variableReference) {
77+
super(format("Variable '%s' has coerced Null value for the non-null 'if' argument of directive '@%s'",
78+
variableReference.getName(), directiveName));
79+
SourceLocation sourceLocation = variableReference.getSourceLocation();
80+
this.sourceLocations = sourceLocation == null ? null : Collections.singletonList(sourceLocation);
81+
}
82+
7583
public NonNullableValueCoercedAsNullException(GraphQLArgument graphQLArgument) {
7684
super(format("Argument '%s' has coerced Null value for NonNull type '%s'", graphQLArgument.getName(), graphQLArgument.getType()));
7785
}

‎src/main/java/graphql/execution/conditional/ConditionalNodes.java‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import graphql.Assert;
44
import graphql.GraphQLContext;
55
import graphql.Internal;
6-
import graphql.execution.AbortExecutionException;
76
import graphql.execution.CoercedVariables;
7+
import graphql.execution.NonNullableValueCoercedAsNullException;
88
import graphql.language.Argument;
99
import graphql.language.BooleanValue;
1010
import graphql.language.Directive;
@@ -147,15 +147,13 @@ public String getIncludeVariableName(DirectivesContainer<?> directivesContainer)
147147
return ((BooleanValue) value).isValue();
148148
}
149149
if (value instanceof VariableReference && variables != null) {
150-
String variableName = ((VariableReference) value).getName();
151-
Object variableValue = variables.get(variableName);
150+
VariableReference variableReference = (VariableReference) value;
151+
Object variableValue = variables.get(variableReference.getName());
152152
// the 'if' argument is Boolean! - a nullable variable with a non null default value is a legal
153153
// usage here, so an explicit null variable value reaches this point and must be rejected as a
154154
// coercion error rather than throwing a NullPointerException while unboxing
155155
if (variableValue == null) {
156-
throw new AbortExecutionException(String.format(
157-
"Variable '%s' has coerced Null value for the non-null 'if' argument of directive '@%s'",
158-
variableName, directiveName));
156+
throw new NonNullableValueCoercedAsNullException(directiveName, variableReference);
159157
}
160158
return (Boolean) variableValue;
161159
}

‎src/test/groovy/graphql/SkipAndInclude.groovy‎

Lines changed: 183 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
11
package graphql
22

3+
import graphql.execution.CoercedVariables
4+
import graphql.execution.NonNullableValueCoercedAsNullException
5+
import graphql.execution.pubsub.CapturingSubscriber
6+
import graphql.execution.pubsub.ReactiveStreamsObjectPublisher
7+
import graphql.language.SourceLocation
8+
import graphql.normalized.ExecutableNormalizedOperationFactory
9+
import graphql.parser.Parser
10+
import graphql.schema.DataFetcher
11+
import org.awaitility.Awaitility
12+
import org.reactivestreams.Publisher
313
import spock.lang.Specification
414

15+
import java.util.concurrent.CompletableFuture
16+
import java.util.concurrent.TimeUnit
17+
518
class SkipAndInclude extends Specification {
619

720
private def graphQL = TestUtil.graphQL("""
@@ -79,26 +92,183 @@ class SkipAndInclude extends Specification {
7992
false | false
8093
}
8194

82-
def "null value for the #directive if argument is a coerced null error, not a NullPointerException"() {
83-
given:
95+
private static GraphQL nestedGraphQL() {
96+
def item = [child: "child"]
97+
def parentFetcher = { env -> item } as DataFetcher
98+
def asyncParentFetcher = { env -> CompletableFuture.supplyAsync({ item }) } as DataFetcher
99+
def eventsFetcher = { env -> new ReactiveStreamsObjectPublisher(2, { i -> item }) } as DataFetcher
100+
def schema = TestUtil.schema("""
101+
type Query {
102+
ok: String
103+
parent: Item
104+
asyncParent: Item
105+
wrapper: Wrapper
106+
items: [Item]
107+
}
108+
type Mutation {
109+
ok: String
110+
parent: Item
111+
}
112+
type Subscription {
113+
event: Item
114+
}
115+
type Wrapper {
116+
inner: Item!
117+
}
118+
type Item {
119+
child: String
120+
}
121+
""", [
122+
Query : [ok: { env -> "ok" } as DataFetcher, parent: parentFetcher, asyncParent: asyncParentFetcher,
123+
wrapper: { env -> [inner: item] } as DataFetcher, items: { env -> [item, item] } as DataFetcher],
124+
Mutation : [ok: { env -> "ok" } as DataFetcher, parent: parentFetcher],
125+
Subscription: [event: eventsFetcher]
126+
])
127+
GraphQL.newGraphQL(schema).build()
128+
}
129+
130+
private static ExecutionInput nullFlagInput(String query) {
131+
ExecutionInput.newExecutionInput().query(query).variables([flag: null]).build()
132+
}
133+
134+
private static String coercedNullMessage(String directive) {
135+
"Variable 'flag' has coerced Null value for the non-null 'if' argument of directive '@$directive'"
136+
}
137+
138+
def "null value for a root #directive if argument is a coercion error with no data"() {
84139
// a nullable variable with a non null default value is a legal usage in the non null 'if' position,
85140
// so an explicit null variable value reaches the directive and must be reported as a coercion error
86-
def executionInput = ExecutionInput.newExecutionInput()
87-
.query("""
88-
query(\$flag: Boolean = true) {
89-
field @$directive(if: \$flag)
90-
}
91-
""")
92-
.variables([flag: null])
93-
.build()
141+
when:
142+
def executionResult = graphQL.execute(nullFlagInput("""query(\$flag: Boolean = true) {
143+
field @$directive(if: \$flag)
144+
}"""))
94145

146+
then:
147+
!executionResult.isDataPresent()
148+
!executionResult.toSpecification().containsKey("data")
149+
executionResult.errors.size() == 1
150+
executionResult.errors[0] instanceof NonNullableValueCoercedAsNullException
151+
executionResult.errors[0].message == coercedNullMessage(directive)
152+
executionResult.errors[0].errorType == ErrorType.ValidationError
153+
executionResult.errors[0].locations == [new SourceLocation(2, 15 + directive.length())]
154+
executionResult.errors[0].path == null
155+
156+
where:
157+
directive << ["skip", "include"]
158+
}
159+
160+
def "null value for a nested #directive if argument nulls the nullable parent of #operation and keeps sibling data"() {
95161
when:
96-
def executionResult = graphQL.execute(executionInput)
162+
def executionResult = nestedGraphQL().execute(nullFlagInput("""$operation(\$flag: Boolean = true) {
163+
ok
164+
parent { child @$directive(if: \$flag) }
165+
}"""))
166+
167+
then:
168+
executionResult.toSpecification().data == [ok: "ok", parent: null]
169+
executionResult.errors.size() == 1
170+
executionResult.errors[0].message == coercedNullMessage(directive)
171+
executionResult.errors[0].errorType == ErrorType.ValidationError
172+
executionResult.errors[0].path == ["parent"]
173+
executionResult.errors[0].locations == [new SourceLocation(3, 24 + directive.length())]
174+
175+
where:
176+
directive | operation
177+
"skip" | "query"
178+
"include" | "query"
179+
"skip" | "mutation"
180+
"include" | "mutation"
181+
}
182+
183+
def "null value for a nested #directive if argument under an async parent nulls that parent"() {
184+
when:
185+
def executionResult = nestedGraphQL().execute(nullFlagInput("""query(\$flag: Boolean = true) {
186+
ok
187+
asyncParent { child @$directive(if: \$flag) }
188+
}"""))
189+
190+
then:
191+
executionResult.toSpecification().data == [ok: "ok", asyncParent: null]
192+
executionResult.errors.size() == 1
193+
executionResult.errors[0].message == coercedNullMessage(directive)
194+
executionResult.errors[0].path == ["asyncParent"]
195+
196+
where:
197+
directive << ["skip", "include"]
198+
}
199+
200+
def "null value for a nested #directive if argument under a non-null parent propagates to the nullable grandparent"() {
201+
when:
202+
def executionResult = nestedGraphQL().execute(nullFlagInput("""query(\$flag: Boolean = true) {
203+
ok
204+
wrapper { inner { child @$directive(if: \$flag) } }
205+
}"""))
97206

98207
then:
99-
executionResult.data == null
208+
executionResult.toSpecification().data == [ok: "ok", wrapper: null]
100209
executionResult.errors.size() == 1
101-
executionResult.errors[0].message.contains("coerced Null value for the non-null 'if' argument of directive '@$directive'")
210+
executionResult.errors[0].message == coercedNullMessage(directive)
211+
executionResult.errors[0].path == ["wrapper", "inner"]
212+
executionResult.errors[0].locations == [new SourceLocation(3, 33 + directive.length())]
213+
214+
where:
215+
directive << ["skip", "include"]
216+
}
217+
218+
def "null value for a nested #directive if argument in a list nulls each list item"() {
219+
when:
220+
def executionResult = nestedGraphQL().execute(nullFlagInput("""query(\$flag: Boolean = true) {
221+
ok
222+
items { child @$directive(if: \$flag) }
223+
}"""))
224+
225+
then:
226+
executionResult.toSpecification().data == [ok: "ok", items: [null, null]]
227+
executionResult.errors*.path == [["items", 0], ["items", 1]]
228+
executionResult.errors.every { it.message == coercedNullMessage(directive) }
229+
230+
where:
231+
directive << ["skip", "include"]
232+
}
233+
234+
def "null value for a nested #directive if argument in a subscription is an error on each event, not a stream failure"() {
235+
when:
236+
def executionResult = nestedGraphQL().execute(nullFlagInput("""subscription(\$flag: Boolean = true) {
237+
event { child @$directive(if: \$flag) }
238+
}"""))
239+
Publisher<ExecutionResult> publisher = executionResult.getData()
240+
def subscriber = new CapturingSubscriber<ExecutionResult>()
241+
publisher.subscribe(subscriber)
242+
Awaitility.await().atMost(10, TimeUnit.SECONDS).untilTrue(subscriber.isDone())
243+
244+
then:
245+
subscriber.throwable == null
246+
subscriber.events.size() == 2
247+
subscriber.events.every { er ->
248+
er.toSpecification().data == [event: null] &&
249+
er.errors.size() == 1 &&
250+
er.errors[0].message == coercedNullMessage(directive) &&
251+
er.errors[0].path == ["event"]
252+
}
253+
254+
where:
255+
directive << ["skip", "include"]
256+
}
257+
258+
def "null value for a #directive if argument is a coercion error when building a normalized operation"() {
259+
given:
260+
def schema = TestUtil.schema("type Query { field: Int }")
261+
def document = new Parser().parseDocument("""query(\$flag: Boolean = true) {
262+
field @$directive(if: \$flag)
263+
}""")
264+
265+
when:
266+
ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(
267+
schema, document, null, CoercedVariables.of([flag: null]))
268+
269+
then:
270+
def e = thrown(NonNullableValueCoercedAsNullException)
271+
e.message == coercedNullMessage(directive)
102272

103273
where:
104274
directive << ["skip", "include"]

0 commit comments

Comments
 (0)