Skip to content

Commit b948b25

Browse files
authored
Merge pull request #710 from schaitoff/master
Improve perf of separateOperations
2 parents 21b34a3 + f801089 commit b948b25

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/utilities/separateOperations.js

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,23 @@ export function separateOperations(
2525
): { [operationName: string]: DocumentNode } {
2626

2727
const operations = [];
28+
const fragments = Object.create(null);
29+
const positions = new Map();
2830
const depGraph: DepGraph = Object.create(null);
2931
let fromName;
32+
let idx = 0;
3033

31-
// Populate the list of operations and build a dependency graph.
34+
// Populate metadata and build a dependency graph.
3235
visit(documentAST, {
3336
OperationDefinition(node) {
34-
operations.push(node);
3537
fromName = opName(node);
38+
operations.push(node);
39+
positions.set(node, idx++);
3640
},
3741
FragmentDefinition(node) {
3842
fromName = node.name.value;
43+
fragments[fromName] = node;
44+
positions.set(node, idx++);
3945
},
4046
FragmentSpread(node) {
4147
const toName = node.name.value;
@@ -52,12 +58,19 @@ export function separateOperations(
5258
const dependencies = Object.create(null);
5359
collectTransitiveDependencies(dependencies, depGraph, operationName);
5460

61+
// The list of definition nodes to be included for this operation, sorted
62+
// to retain the same order as the original document.
63+
const definitions = [ operation ];
64+
Object.keys(dependencies).forEach(name => {
65+
definitions.push(fragments[name]);
66+
});
67+
definitions.sort(
68+
(n1, n2) => (positions.get(n1) || 0) - (positions.get(n2) || 0)
69+
);
70+
5571
separatedDocumentASTs[operationName] = {
5672
kind: 'Document',
57-
definitions: documentAST.definitions.filter(def =>
58-
def === operation ||
59-
def.kind === 'FragmentDefinition' && dependencies[def.name.value]
60-
)
73+
definitions
6174
};
6275
});
6376

0 commit comments

Comments
 (0)