Skip to content

Commit f726196

Browse files
IvanGoncharovleebyron
authored andcommitted
Refactor NoFragmentCycles rule (#1381)
1 parent f2070c8 commit f726196

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

src/validation/rules/NoFragmentCycles.js

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@ export function NoFragmentCycles(context: ValidationContext): ASTVisitor {
3434
return {
3535
OperationDefinition: () => false,
3636
FragmentDefinition(node) {
37-
if (!visitedFrags[node.name.value]) {
38-
detectCycleRecursive(node);
39-
}
37+
detectCycleRecursive(node);
4038
return false;
4139
},
4240
};
@@ -45,6 +43,10 @@ export function NoFragmentCycles(context: ValidationContext): ASTVisitor {
4543
// It does not terminate when a cycle was found but continues to explore
4644
// the graph to find all possible cycles.
4745
function detectCycleRecursive(fragment: FragmentDefinitionNode) {
46+
if (visitedFrags[fragment.name.value]) {
47+
return;
48+
}
49+
4850
const fragmentName = fragment.name.value;
4951
visitedFrags[fragmentName] = true;
5052

@@ -60,24 +62,23 @@ export function NoFragmentCycles(context: ValidationContext): ASTVisitor {
6062
const spreadName = spreadNode.name.value;
6163
const cycleIndex = spreadPathIndexByName[spreadName];
6264

65+
spreadPath.push(spreadNode);
6366
if (cycleIndex === undefined) {
64-
spreadPath.push(spreadNode);
65-
if (!visitedFrags[spreadName]) {
66-
const spreadFragment = context.getFragment(spreadName);
67-
if (spreadFragment) {
68-
detectCycleRecursive(spreadFragment);
69-
}
67+
const spreadFragment = context.getFragment(spreadName);
68+
if (spreadFragment) {
69+
detectCycleRecursive(spreadFragment);
7070
}
71-
spreadPath.pop();
7271
} else {
7372
const cyclePath = spreadPath.slice(cycleIndex);
73+
const fragmentNames = cyclePath.slice(0, -1).map(s => s.name.value);
7474
context.reportError(
7575
new GraphQLError(
76-
cycleErrorMessage(spreadName, cyclePath.map(s => s.name.value)),
77-
cyclePath.concat(spreadNode),
76+
cycleErrorMessage(spreadName, fragmentNames),
77+
cyclePath,
7878
),
7979
);
8080
}
81+
spreadPath.pop();
8182
}
8283

8384
spreadPathIndexByName[fragmentName] = undefined;

0 commit comments

Comments
 (0)