UniqueDirectivesPerLocationRule.mjs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { GraphQLError } from '../../error/GraphQLError.mjs';
  2. import { Kind } from '../../language/kinds.mjs';
  3. import {
  4. isTypeDefinitionNode,
  5. isTypeExtensionNode,
  6. } from '../../language/predicates.mjs';
  7. import { specifiedDirectives } from '../../type/directives.mjs';
  8. /**
  9. * Unique directive names per location
  10. *
  11. * A GraphQL document is only valid if all non-repeatable directives at
  12. * a given location are uniquely named.
  13. *
  14. * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location
  15. */
  16. export function UniqueDirectivesPerLocationRule(context) {
  17. const uniqueDirectiveMap = Object.create(null);
  18. const schema = context.getSchema();
  19. const definedDirectives = schema
  20. ? schema.getDirectives()
  21. : specifiedDirectives;
  22. for (const directive of definedDirectives) {
  23. uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
  24. }
  25. const astDefinitions = context.getDocument().definitions;
  26. for (const def of astDefinitions) {
  27. if (def.kind === Kind.DIRECTIVE_DEFINITION) {
  28. uniqueDirectiveMap[def.name.value] = !def.repeatable;
  29. }
  30. }
  31. const schemaDirectives = Object.create(null);
  32. const typeDirectivesMap = Object.create(null);
  33. return {
  34. // Many different AST nodes may contain directives. Rather than listing
  35. // them all, just listen for entering any node, and check to see if it
  36. // defines any directives.
  37. enter(node) {
  38. if (!('directives' in node) || !node.directives) {
  39. return;
  40. }
  41. let seenDirectives;
  42. if (
  43. node.kind === Kind.SCHEMA_DEFINITION ||
  44. node.kind === Kind.SCHEMA_EXTENSION
  45. ) {
  46. seenDirectives = schemaDirectives;
  47. } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) {
  48. const typeName = node.name.value;
  49. seenDirectives = typeDirectivesMap[typeName];
  50. if (seenDirectives === undefined) {
  51. typeDirectivesMap[typeName] = seenDirectives = Object.create(null);
  52. }
  53. } else {
  54. seenDirectives = Object.create(null);
  55. }
  56. for (const directive of node.directives) {
  57. const directiveName = directive.name.value;
  58. if (uniqueDirectiveMap[directiveName]) {
  59. if (seenDirectives[directiveName]) {
  60. context.reportError(
  61. new GraphQLError(
  62. `The directive "@${directiveName}" can only be used once at this location.`,
  63. {
  64. nodes: [seenDirectives[directiveName], directive],
  65. },
  66. ),
  67. );
  68. } else {
  69. seenDirectives[directiveName] = directive;
  70. }
  71. }
  72. }
  73. },
  74. };
  75. }