Skip to content

Commit e2a6f23

Browse files
committed
separateOperations: simplify algorithm
1 parent b3b1b04 commit e2a6f23

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

src/utilities/separateOperations.js

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { type ObjMap } from '../jsutils/ObjMap';
44

5+
import { Kind } from '../language/kinds';
56
import { visit } from '../language/visitor';
67
import {
78
type DocumentNode,
@@ -18,29 +19,25 @@ export function separateOperations(
1819
documentAST: DocumentNode,
1920
): ObjMap<DocumentNode> {
2021
const operations = [];
21-
const fragments = Object.create(null);
22-
const positions = new Map();
2322
const depGraph: DepGraph = Object.create(null);
2423
let fromName;
25-
let idx = 0;
2624

2725
// Populate metadata and build a dependency graph.
2826
visit(documentAST, {
2927
OperationDefinition(node) {
3028
fromName = opName(node);
3129
operations.push(node);
32-
positions.set(node, idx++);
3330
},
3431
FragmentDefinition(node) {
3532
fromName = node.name.value;
36-
fragments[fromName] = node;
37-
positions.set(node, idx++);
3833
},
3934
FragmentSpread(node) {
4035
const toName = node.name.value;
41-
(depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[
42-
toName
43-
] = true;
36+
let dependents = depGraph[fromName];
37+
if (dependents === undefined) {
38+
dependents = depGraph[fromName] = Object.create(null);
39+
}
40+
dependents[toName] = true;
4441
},
4542
});
4643

@@ -54,17 +51,14 @@ export function separateOperations(
5451

5552
// The list of definition nodes to be included for this operation, sorted
5653
// to retain the same order as the original document.
57-
const definitions = [operation];
58-
for (const name of Object.keys(dependencies)) {
59-
definitions.push(fragments[name]);
60-
}
61-
definitions.sort(
62-
(n1, n2) => (positions.get(n1) || 0) - (positions.get(n2) || 0),
63-
);
64-
6554
separatedDocumentASTs[operationName] = {
66-
kind: 'Document',
67-
definitions,
55+
kind: Kind.DOCUMENT,
56+
definitions: documentAST.definitions.filter(
57+
node =>
58+
node === operation ||
59+
(node.kind === Kind.FRAGMENT_DEFINITION &&
60+
dependencies[node.name.value]),
61+
),
6862
};
6963
}
7064

0 commit comments

Comments
 (0)