Skip to content

Commit 2c3abcc

Browse files
feature: Adds NoUndefinedVariablesRule
1 parent 14949c7 commit 2c3abcc

File tree

3 files changed

+464
-1
lines changed

3 files changed

+464
-1
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
/**
3+
* No undefined variables
4+
*
5+
* A GraphQL operation is only valid if all variables encountered, both directly
6+
* and via fragment spreads, are defined by that operation.
7+
*
8+
* See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined
9+
*/
10+
func NoUndefinedVariablesRule(context: ValidationContext) -> Visitor {
11+
return Visitor(
12+
enter: { node, _, _, _, _ in
13+
if let operation = node as? OperationDefinition {
14+
let variableNameDefined = Set<String>(
15+
operation.variableDefinitions.map { $0.variable.name.value }
16+
)
17+
18+
let usages = context.getRecursiveVariableUsages(operation: operation)
19+
for usage in usages {
20+
let node = usage.node
21+
let varName = node.name.value
22+
if !variableNameDefined.contains(varName) {
23+
let message: String
24+
if let operationName = operation.name {
25+
message =
26+
"Variable \"$\(varName)\" is not defined by operation \"\(operationName.value)\"."
27+
} else {
28+
message = "Variable \"$\(varName)\" is not defined."
29+
}
30+
context.report(
31+
error: GraphQLError(
32+
message: message,
33+
nodes: [node, operation]
34+
)
35+
)
36+
}
37+
}
38+
}
39+
return .continue
40+
}
41+
)
42+
}

Sources/GraphQL/Validation/SpecifiedRules.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public let specifiedRules: [(ValidationContext) -> Visitor] = [
1717
PossibleFragmentSpreadsRule,
1818
NoFragmentCyclesRule,
1919
UniqueVariableNamesRule,
20-
// NoUndefinedVariablesRule,
20+
NoUndefinedVariablesRule,
2121
NoUnusedVariablesRule,
2222
// KnownDirectivesRule,
2323
// UniqueDirectivesPerLocationRule,

0 commit comments

Comments
 (0)