UniqueOperationNames.js.flow 1.1 KB

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