NoUnusedVariables.mjs 1.5 KB

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