NoUndefinedVariablesRule.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { GraphQLError } from "../../error/GraphQLError.mjs";
  2. /**
  3. * No undefined variables
  4. *
  5. * A GraphQL operation is only valid if all variables encountered, both directly
  6. * and via fragment spreads, are defined by that operation.
  7. */
  8. export function NoUndefinedVariablesRule(context) {
  9. var variableNameDefined = Object.create(null);
  10. return {
  11. OperationDefinition: {
  12. enter: function enter() {
  13. variableNameDefined = Object.create(null);
  14. },
  15. leave: function leave(operation) {
  16. var usages = context.getRecursiveVariableUsages(operation);
  17. for (var _i2 = 0; _i2 < usages.length; _i2++) {
  18. var _ref2 = usages[_i2];
  19. var node = _ref2.node;
  20. var varName = node.name.value;
  21. if (variableNameDefined[varName] !== true) {
  22. context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(varName, "\" is not defined."), [node, operation]));
  23. }
  24. }
  25. }
  26. },
  27. VariableDefinition: function VariableDefinition(node) {
  28. variableNameDefined[node.variable.name.value] = true;
  29. }
  30. };
  31. }