UniqueArgumentNamesRule.mjs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { groupBy } from '../../jsutils/groupBy.mjs';
  2. import { GraphQLError } from '../../error/GraphQLError.mjs';
  3. /**
  4. * Unique argument names
  5. *
  6. * A GraphQL field or directive is only valid if all supplied arguments are
  7. * uniquely named.
  8. *
  9. * See https://spec.graphql.org/draft/#sec-Argument-Names
  10. */
  11. export function UniqueArgumentNamesRule(context) {
  12. return {
  13. Field: checkArgUniqueness,
  14. Directive: checkArgUniqueness,
  15. };
  16. function checkArgUniqueness(parentNode) {
  17. var _parentNode$arguments;
  18. // FIXME: https://github.com/graphql/graphql-js/issues/2203
  19. /* c8 ignore next */
  20. const argumentNodes =
  21. (_parentNode$arguments = parentNode.arguments) !== null &&
  22. _parentNode$arguments !== void 0
  23. ? _parentNode$arguments
  24. : [];
  25. const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value);
  26. for (const [argName, argNodes] of seenArgs) {
  27. if (argNodes.length > 1) {
  28. context.reportError(
  29. new GraphQLError(
  30. `There can be only one argument named "${argName}".`,
  31. {
  32. nodes: argNodes.map((node) => node.name),
  33. },
  34. ),
  35. );
  36. }
  37. }
  38. }
  39. }