NoUnusedFragmentsRule.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used
  14. */
  15. function NoUnusedFragmentsRule(context) {
  16. const operationDefs = [];
  17. const fragmentDefs = [];
  18. return {
  19. OperationDefinition(node) {
  20. operationDefs.push(node);
  21. return false;
  22. },
  23. FragmentDefinition(node) {
  24. fragmentDefs.push(node);
  25. return false;
  26. },
  27. Document: {
  28. leave() {
  29. const fragmentNameUsed = Object.create(null);
  30. for (const operation of operationDefs) {
  31. for (const fragment of context.getRecursivelyReferencedFragments(
  32. operation,
  33. )) {
  34. fragmentNameUsed[fragment.name.value] = true;
  35. }
  36. }
  37. for (const fragmentDef of fragmentDefs) {
  38. const fragName = fragmentDef.name.value;
  39. if (fragmentNameUsed[fragName] !== true) {
  40. context.reportError(
  41. new _GraphQLError.GraphQLError(
  42. `Fragment "${fragName}" is never used.`,
  43. {
  44. nodes: fragmentDef,
  45. },
  46. ),
  47. );
  48. }
  49. }
  50. },
  51. },
  52. };
  53. }