graphql
Version:
A Query Language and Runtime which can target any service.
70 lines (66 loc) • 2.35 kB
JavaScript
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* strict
*/
import { GraphQLError } from '../../error/GraphQLError';
export function unusedVariableMessage(varName, opName) {
return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used.");
}
/**
* No unused variables
*
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
export function NoUnusedVariables(context) {
var variableDefs = [];
return {
OperationDefinition: {
enter: function enter() {
variableDefs = [];
},
leave: function leave(operation) {
var variableNameUsed = Object.create(null);
var usages = context.getRecursiveVariableUsages(operation);
var opName = operation.name ? operation.name.value : null;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _ref2 = _step.value;
var node = _ref2.node;
variableNameUsed[node.name.value] = true;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
for (var _i = 0; _i < variableDefs.length; _i++) {
var variableDef = variableDefs[_i];
var variableName = variableDef.variable.name.value;
if (variableNameUsed[variableName] !== true) {
context.reportError(new GraphQLError(unusedVariableMessage(variableName, opName), [variableDef]));
}
}
}
},
VariableDefinition: function VariableDefinition(def) {
variableDefs.push(def);
}
};
}