UNPKG

1.41 kBJavaScriptView Raw
1import { GraphQLError } from "../../error/GraphQLError.mjs";
2
3/**
4 * No unused variables
5 *
6 * A GraphQL operation is only valid if all variables defined by an operation
7 * are used, either directly or within a spread fragment.
8 */
9export function NoUnusedVariablesRule(context) {
10 var variableDefs = [];
11 return {
12 OperationDefinition: {
13 enter: function enter() {
14 variableDefs = [];
15 },
16 leave: function leave(operation) {
17 var variableNameUsed = Object.create(null);
18 var usages = context.getRecursiveVariableUsages(operation);
19
20 for (var _i2 = 0; _i2 < usages.length; _i2++) {
21 var _ref2 = usages[_i2];
22 var node = _ref2.node;
23 variableNameUsed[node.name.value] = true;
24 }
25
26 for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) {
27 var variableDef = _variableDefs2[_i4];
28 var variableName = variableDef.variable.name.value;
29
30 if (variableNameUsed[variableName] !== true) {
31 context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(variableName, "\" is never used in operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(variableName, "\" is never used."), variableDef));
32 }
33 }
34 }
35 },
36 VariableDefinition: function VariableDefinition(def) {
37 variableDefs.push(def);
38 }
39 };
40}