NoUnusedVariablesRule.mjs 1.4 KB

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