UniqueDirectivesPerLocation.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.duplicateDirectiveMessage = duplicateDirectiveMessage;
  6. exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation;
  7. var _GraphQLError = require("../../error/GraphQLError");
  8. var _kinds = require("../../language/kinds");
  9. var _directives = require("../../type/directives");
  10. function duplicateDirectiveMessage(directiveName) {
  11. return "The directive \"".concat(directiveName, "\" can only be used once at this location.");
  12. }
  13. /**
  14. * Unique directive names per location
  15. *
  16. * A GraphQL document is only valid if all non-repeatable directives at
  17. * a given location are uniquely named.
  18. */
  19. function UniqueDirectivesPerLocation(context) {
  20. var uniqueDirectiveMap = Object.create(null);
  21. var schema = context.getSchema();
  22. var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
  23. for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
  24. var directive = definedDirectives[_i2];
  25. uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
  26. }
  27. var astDefinitions = context.getDocument().definitions;
  28. for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
  29. var def = astDefinitions[_i4];
  30. if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
  31. uniqueDirectiveMap[def.name.value] = !def.repeatable;
  32. }
  33. }
  34. return {
  35. // Many different AST nodes may contain directives. Rather than listing
  36. // them all, just listen for entering any node, and check to see if it
  37. // defines any directives.
  38. enter: function enter(node) {
  39. // Flow can't refine that node.directives will only contain directives,
  40. // so we cast so the rest of the code is well typed.
  41. var directives = node.directives;
  42. if (directives) {
  43. var knownDirectives = Object.create(null);
  44. for (var _i6 = 0; _i6 < directives.length; _i6++) {
  45. var _directive = directives[_i6];
  46. var directiveName = _directive.name.value;
  47. if (uniqueDirectiveMap[directiveName]) {
  48. if (knownDirectives[directiveName]) {
  49. context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], _directive]));
  50. } else {
  51. knownDirectives[directiveName] = _directive;
  52. }
  53. }
  54. }
  55. }
  56. }
  57. };
  58. }