NoUnusedFragmentsRule.mjs 1.4 KB

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