NoUndefinedVariablesRule.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule;
  6. var _GraphQLError = require('../../error/GraphQLError.js');
  7. /**
  8. * No undefined variables
  9. *
  10. * A GraphQL operation is only valid if all variables encountered, both directly
  11. * and via fragment spreads, are defined by that operation.
  12. *
  13. * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined
  14. */
  15. function NoUndefinedVariablesRule(context) {
  16. let variableNameDefined = Object.create(null);
  17. return {
  18. OperationDefinition: {
  19. enter() {
  20. variableNameDefined = Object.create(null);
  21. },
  22. leave(operation) {
  23. const usages = context.getRecursiveVariableUsages(operation);
  24. for (const { node } of usages) {
  25. const varName = node.name.value;
  26. if (variableNameDefined[varName] !== true) {
  27. context.reportError(
  28. new _GraphQLError.GraphQLError(
  29. operation.name
  30. ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".`
  31. : `Variable "$${varName}" is not defined.`,
  32. {
  33. nodes: [node, operation],
  34. },
  35. ),
  36. );
  37. }
  38. }
  39. },
  40. },
  41. VariableDefinition(node) {
  42. variableNameDefined[node.variable.name.value] = true;
  43. },
  44. };
  45. }