NoUnusedFragments.js 1.7 KB

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