UniqueInputFieldNames.js.flow 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 duplicateInputFieldMessage(fieldName: string): string {
  6. return `There can be only one input field named "${fieldName}".`;
  7. }
  8. /**
  9. * Unique input field names
  10. *
  11. * A GraphQL input object value is only valid if all supplied fields are
  12. * uniquely named.
  13. */
  14. export function UniqueInputFieldNames(
  15. context: ASTValidationContext,
  16. ): ASTVisitor {
  17. const knownNameStack = [];
  18. let knownNames = Object.create(null);
  19. return {
  20. ObjectValue: {
  21. enter() {
  22. knownNameStack.push(knownNames);
  23. knownNames = Object.create(null);
  24. },
  25. leave() {
  26. knownNames = knownNameStack.pop();
  27. },
  28. },
  29. ObjectField(node) {
  30. const fieldName = node.name.value;
  31. if (knownNames[fieldName]) {
  32. context.reportError(
  33. new GraphQLError(duplicateInputFieldMessage(fieldName), [
  34. knownNames[fieldName],
  35. node.name,
  36. ]),
  37. );
  38. } else {
  39. knownNames[fieldName] = node.name;
  40. }
  41. },
  42. };
  43. }