UniqueDirectiveNamesRule.mjs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { GraphQLError } from '../../error/GraphQLError.mjs';
  2. /**
  3. * Unique directive names
  4. *
  5. * A GraphQL document is only valid if all defined directives have unique names.
  6. */
  7. export function UniqueDirectiveNamesRule(context) {
  8. const knownDirectiveNames = Object.create(null);
  9. const schema = context.getSchema();
  10. return {
  11. DirectiveDefinition(node) {
  12. const directiveName = node.name.value;
  13. if (
  14. schema !== null &&
  15. schema !== void 0 &&
  16. schema.getDirective(directiveName)
  17. ) {
  18. context.reportError(
  19. new GraphQLError(
  20. `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`,
  21. {
  22. nodes: node.name,
  23. },
  24. ),
  25. );
  26. return;
  27. }
  28. if (knownDirectiveNames[directiveName]) {
  29. context.reportError(
  30. new GraphQLError(
  31. `There can be only one directive named "@${directiveName}".`,
  32. {
  33. nodes: [knownDirectiveNames[directiveName], node.name],
  34. },
  35. ),
  36. );
  37. } else {
  38. knownDirectiveNames[directiveName] = node.name;
  39. }
  40. return false;
  41. },
  42. };
  43. }