NoUnusedFragmentsRule.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule;
  6. var _GraphQLError = require("../../error/GraphQLError.js");
  7. /**
  8. * No unused fragments
  9. *
  10. * A GraphQL document is only valid if all fragment definitions are spread
  11. * within operations, or spread within other fragments spread within operations.
  12. */
  13. function NoUnusedFragmentsRule(context) {
  14. var operationDefs = [];
  15. var fragmentDefs = [];
  16. return {
  17. OperationDefinition: function OperationDefinition(node) {
  18. operationDefs.push(node);
  19. return false;
  20. },
  21. FragmentDefinition: function FragmentDefinition(node) {
  22. fragmentDefs.push(node);
  23. return false;
  24. },
  25. Document: {
  26. leave: function leave() {
  27. var fragmentNameUsed = Object.create(null);
  28. for (var _i2 = 0; _i2 < operationDefs.length; _i2++) {
  29. var operation = operationDefs[_i2];
  30. for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) {
  31. var fragment = _context$getRecursive2[_i4];
  32. fragmentNameUsed[fragment.name.value] = true;
  33. }
  34. }
  35. for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) {
  36. var fragmentDef = fragmentDefs[_i6];
  37. var fragName = fragmentDef.name.value;
  38. if (fragmentNameUsed[fragName] !== true) {
  39. context.reportError(new _GraphQLError.GraphQLError("Fragment \"".concat(fragName, "\" is never used."), fragmentDef));
  40. }
  41. }
  42. }
  43. }
  44. };
  45. }