UniqueVariableNamesRule.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.UniqueVariableNamesRule = UniqueVariableNamesRule;
  6. var _groupBy = require('../../jsutils/groupBy.js');
  7. var _GraphQLError = require('../../error/GraphQLError.js');
  8. /**
  9. * Unique variable names
  10. *
  11. * A GraphQL operation is only valid if all its variables are uniquely named.
  12. */
  13. function UniqueVariableNamesRule(context) {
  14. return {
  15. OperationDefinition(operationNode) {
  16. var _operationNode$variab;
  17. // See: https://github.com/graphql/graphql-js/issues/2203
  18. /* c8 ignore next */
  19. const variableDefinitions =
  20. (_operationNode$variab = operationNode.variableDefinitions) !== null &&
  21. _operationNode$variab !== void 0
  22. ? _operationNode$variab
  23. : [];
  24. const seenVariableDefinitions = (0, _groupBy.groupBy)(
  25. variableDefinitions,
  26. (node) => node.variable.name.value,
  27. );
  28. for (const [variableName, variableNodes] of seenVariableDefinitions) {
  29. if (variableNodes.length > 1) {
  30. context.reportError(
  31. new _GraphQLError.GraphQLError(
  32. `There can be only one variable named "$${variableName}".`,
  33. {
  34. nodes: variableNodes.map((node) => node.variable.name),
  35. },
  36. ),
  37. );
  38. }
  39. }
  40. },
  41. };
  42. }