NoFragmentCycles.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.cycleErrorMessage = cycleErrorMessage;
  6. exports.NoFragmentCycles = NoFragmentCycles;
  7. var _GraphQLError = require("../../error/GraphQLError");
  8. function cycleErrorMessage(fragName, spreadNames) {
  9. var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
  10. return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, ".");
  11. }
  12. function NoFragmentCycles(context) {
  13. // Tracks already visited fragments to maintain O(N) and to ensure that cycles
  14. // are not redundantly reported.
  15. var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
  16. var spreadPath = []; // Position in the spread path
  17. var spreadPathIndexByName = Object.create(null);
  18. return {
  19. OperationDefinition: function OperationDefinition() {
  20. return false;
  21. },
  22. FragmentDefinition: function FragmentDefinition(node) {
  23. detectCycleRecursive(node);
  24. return false;
  25. }
  26. }; // This does a straight-forward DFS to find cycles.
  27. // It does not terminate when a cycle was found but continues to explore
  28. // the graph to find all possible cycles.
  29. function detectCycleRecursive(fragment) {
  30. if (visitedFrags[fragment.name.value]) {
  31. return;
  32. }
  33. var fragmentName = fragment.name.value;
  34. visitedFrags[fragmentName] = true;
  35. var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
  36. if (spreadNodes.length === 0) {
  37. return;
  38. }
  39. spreadPathIndexByName[fragmentName] = spreadPath.length;
  40. for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) {
  41. var spreadNode = spreadNodes[_i2];
  42. var spreadName = spreadNode.name.value;
  43. var cycleIndex = spreadPathIndexByName[spreadName];
  44. spreadPath.push(spreadNode);
  45. if (cycleIndex === undefined) {
  46. var spreadFragment = context.getFragment(spreadName);
  47. if (spreadFragment) {
  48. detectCycleRecursive(spreadFragment);
  49. }
  50. } else {
  51. var cyclePath = spreadPath.slice(cycleIndex);
  52. var fragmentNames = cyclePath.slice(0, -1).map(function (s) {
  53. return s.name.value;
  54. });
  55. context.reportError(new _GraphQLError.GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath));
  56. }
  57. spreadPath.pop();
  58. }
  59. spreadPathIndexByName[fragmentName] = undefined;
  60. }
  61. }