NoFragmentCyclesRule.js 2.2 KB

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