NoFragmentCyclesRule.js.flow 2.3 KB

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