UniqueArgumentNames.js.flow 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import { type ASTVisitor } from '../../language/visitor';
  4. import { type ASTValidationContext } from '../ValidationContext';
  5. export function duplicateArgMessage(argName: string): string {
  6. return `There can be only one argument named "${argName}".`;
  7. }
  8. /**
  9. * Unique argument names
  10. *
  11. * A GraphQL field or directive is only valid if all supplied arguments are
  12. * uniquely named.
  13. */
  14. export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor {
  15. let knownArgNames = Object.create(null);
  16. return {
  17. Field() {
  18. knownArgNames = Object.create(null);
  19. },
  20. Directive() {
  21. knownArgNames = Object.create(null);
  22. },
  23. Argument(node) {
  24. const argName = node.name.value;
  25. if (knownArgNames[argName]) {
  26. context.reportError(
  27. new GraphQLError(duplicateArgMessage(argName), [
  28. knownArgNames[argName],
  29. node.name,
  30. ]),
  31. );
  32. } else {
  33. knownArgNames[argName] = node.name;
  34. }
  35. return false;
  36. },
  37. };
  38. }