UniqueOperationNamesRule.mjs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { GraphQLError } from '../../error/GraphQLError.mjs';
  2. /**
  3. * Unique operation names
  4. *
  5. * A GraphQL document is only valid if all defined operations have unique names.
  6. *
  7. * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness
  8. */
  9. export function UniqueOperationNamesRule(context) {
  10. const knownOperationNames = Object.create(null);
  11. return {
  12. OperationDefinition(node) {
  13. const operationName = node.name;
  14. if (operationName) {
  15. if (knownOperationNames[operationName.value]) {
  16. context.reportError(
  17. new GraphQLError(
  18. `There can be only one operation named "${operationName.value}".`,
  19. {
  20. nodes: [
  21. knownOperationNames[operationName.value],
  22. operationName,
  23. ],
  24. },
  25. ),
  26. );
  27. } else {
  28. knownOperationNames[operationName.value] = operationName;
  29. }
  30. }
  31. return false;
  32. },
  33. FragmentDefinition: () => false,
  34. };
  35. }