UniqueInputFieldNamesRule.js.flow 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. }