Skip to content

Commit 2aa8e9f

Browse files
sportlabsMikepaulofaria
authored andcommitted
Handle the case where a not-required variable is omitted in a query (#17)
1 parent 2deb22b commit 2aa8e9f

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Sources/GraphQL/Execution/Values.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,11 @@ func getVariableValue(schema: GraphQLSchema, definitionAST: VariableDefinition,
7979
if let defaultValue = definitionAST.defaultValue {
8080
return try valueFromAST(valueAST: defaultValue, type: inputType)!
8181
}
82+
else if !(inputType is GraphQLNonNull) {
83+
return .null
84+
}
8285
}
83-
86+
8487
return try coerceValue(type: inputType, value: input)!
8588
}
8689

Tests/GraphQLTests/StarWarsTests/StarWarsQueryTests.swift

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,49 @@ class StarWarsQueryTests : XCTestCase {
126126
XCTAssertEqual(result, expected)
127127
}
128128

129+
func testOptionalVariable() throws{
130+
131+
let query = "query FetchHeroByEpisodeQuery($episode: String) {" +
132+
" hero(episode: $episode) {" +
133+
" name" +
134+
" }" +
135+
"}"
136+
137+
var params: [String: Map]
138+
var expected: Map
139+
var result: Map
140+
141+
// $episode is not required so we can omit and expect this to work and return R2
142+
params = [:]
143+
144+
expected = [
145+
"data": [
146+
"hero": [
147+
"name": "R2-D2",
148+
],
149+
],
150+
]
151+
152+
result = try graphql(schema: StarWarsSchema, request: query, variableValues: params)
153+
XCTAssertEqual(result, expected)
154+
155+
// or we can pass "EMPIRE" and expect Luke
156+
params = [
157+
"episode": "EMPIRE",
158+
]
159+
160+
expected = [
161+
"data": [
162+
"hero": [
163+
"name": "Luke Skywalker",
164+
],
165+
],
166+
]
167+
168+
result = try graphql(schema: StarWarsSchema, request: query, variableValues: params)
169+
XCTAssertEqual(result, expected)
170+
}
171+
129172
func testFetchSomeIDQuery() throws {
130173
let query = "query FetchSomeIDQuery($someId: String!) {" +
131174
" human(id: $someId) {" +

0 commit comments

Comments
 (0)