UniqueVariableNamesRule.mjs 1.2 KB

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