NoUnusedVariablesRule.js 1.5 KB

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