Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor NoFragmentCycles rule #1381

Merged
merged 1 commit into from Jun 12, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 13 additions & 12 deletions src/validation/rules/NoFragmentCycles.js
Expand Up @@ -34,9 +34,7 @@ export function NoFragmentCycles(context: ValidationContext): ASTVisitor {
return {
OperationDefinition: () => false,
FragmentDefinition(node) {
if (!visitedFrags[node.name.value]) {
detectCycleRecursive(node);
}
detectCycleRecursive(node);
return false;
},
};
Expand All @@ -45,6 +43,10 @@ export function NoFragmentCycles(context: ValidationContext): ASTVisitor {
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
function detectCycleRecursive(fragment: FragmentDefinitionNode) {
if (visitedFrags[fragment.name.value]) {
return;
}

const fragmentName = fragment.name.value;
visitedFrags[fragmentName] = true;

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

spreadPath.push(spreadNode);
if (cycleIndex === undefined) {
spreadPath.push(spreadNode);
if (!visitedFrags[spreadName]) {
const spreadFragment = context.getFragment(spreadName);
if (spreadFragment) {
detectCycleRecursive(spreadFragment);
}
const spreadFragment = context.getFragment(spreadName);
if (spreadFragment) {
detectCycleRecursive(spreadFragment);
}
spreadPath.pop();
} else {
const cyclePath = spreadPath.slice(cycleIndex);
const fragmentNames = cyclePath.slice(0, -1).map(s => s.name.value);
context.reportError(
new GraphQLError(
cycleErrorMessage(spreadName, cyclePath.map(s => s.name.value)),
cyclePath.concat(spreadNode),
cycleErrorMessage(spreadName, fragmentNames),
cyclePath,
),
);
}
spreadPath.pop();
}

spreadPathIndexByName[fragmentName] = undefined;
Expand Down