NoUnusedVariablesRule.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. * See https://spec.graphql.org/draft/#sec-All-Variables-Used
  9. */
  10. export function NoUnusedVariablesRule(context) {
  11. let variableDefs = [];
  12. return {
  13. OperationDefinition: {
  14. enter() {
  15. variableDefs = [];
  16. },
  17. leave(operation) {
  18. const variableNameUsed = Object.create(null);
  19. const usages = context.getRecursiveVariableUsages(operation);
  20. for (const { node } of usages) {
  21. variableNameUsed[node.name.value] = true;
  22. }
  23. for (const variableDef of variableDefs) {
  24. const variableName = variableDef.variable.name.value;
  25. if (variableNameUsed[variableName] !== true) {
  26. context.reportError(
  27. new GraphQLError(
  28. operation.name
  29. ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".`
  30. : `Variable "$${variableName}" is never used.`,
  31. {
  32. nodes: variableDef,
  33. },
  34. ),
  35. );
  36. }
  37. }
  38. },
  39. },
  40. VariableDefinition(def) {
  41. variableDefs.push(def);
  42. },
  43. };
  44. }