UniqueOperationNamesRule.js.flow 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  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 operation names
  7. *
  8. * A GraphQL document is only valid if all defined operations have unique names.
  9. */
  10. export function UniqueOperationNamesRule(
  11. context: ASTValidationContext,
  12. ): ASTVisitor {
  13. const knownOperationNames = Object.create(null);
  14. return {
  15. OperationDefinition(node) {
  16. const operationName = node.name;
  17. if (operationName) {
  18. if (knownOperationNames[operationName.value]) {
  19. context.reportError(
  20. new GraphQLError(
  21. `There can be only one operation named "${operationName.value}".`,
  22. [knownOperationNames[operationName.value], operationName],
  23. ),
  24. );
  25. } else {
  26. knownOperationNames[operationName.value] = operationName;
  27. }
  28. }
  29. return false;
  30. },
  31. FragmentDefinition: () => false,
  32. };
  33. }