NoUnusedVariables.js 1.7 KB

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