UNPKG

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