UniqueInputFieldNamesRule.js.flow 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import type { ASTVisitor } from '../../language/visitor';
  4. import type { ASTValidationContext } from '../ValidationContext';
  5. /**
  6. * Unique input field names
  7. *
  8. * A GraphQL input object value is only valid if all supplied fields are
  9. * uniquely named.
  10. */
  11. export function UniqueInputFieldNamesRule(
  12. context: ASTValidationContext,
  13. ): ASTVisitor {
  14. const knownNameStack = [];
  15. let knownNames = Object.create(null);
  16. return {
  17. ObjectValue: {
  18. enter() {
  19. knownNameStack.push(knownNames);
  20. knownNames = Object.create(null);
  21. },
  22. leave() {
  23. knownNames = knownNameStack.pop();
  24. },
  25. },
  26. ObjectField(node) {
  27. const fieldName = node.name.value;
  28. if (knownNames[fieldName]) {
  29. context.reportError(
  30. new GraphQLError(
  31. `There can be only one input field named "${fieldName}".`,
  32. [knownNames[fieldName], node.name],
  33. ),
  34. );
  35. } else {
  36. knownNames[fieldName] = node.name;
  37. }
  38. },
  39. };
  40. }