NoUnusedVariablesRule.js 1.5 KB

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