NoUnusedFragments.mjs 1.5 KB

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