@@ -25,17 +25,23 @@ export function separateOperations(
25
25
) : { [ operationName : string ] : DocumentNode } {
26
26
27
27
const operations = [ ] ;
28
+ const fragments = Object . create ( null ) ;
29
+ const positions = new Map ( ) ;
28
30
const depGraph : DepGraph = Object . create ( null ) ;
29
31
let fromName ;
32
+ let idx = 0 ;
30
33
31
- // Populate the list of operations and build a dependency graph.
34
+ // Populate metadata and build a dependency graph.
32
35
visit ( documentAST , {
33
36
OperationDefinition ( node ) {
34
- operations . push ( node ) ;
35
37
fromName = opName ( node ) ;
38
+ operations . push ( node ) ;
39
+ positions . set ( node , idx ++ ) ;
36
40
} ,
37
41
FragmentDefinition ( node ) {
38
42
fromName = node . name . value ;
43
+ fragments [ fromName ] = node ;
44
+ positions . set ( node , idx ++ ) ;
39
45
} ,
40
46
FragmentSpread ( node ) {
41
47
const toName = node . name . value ;
@@ -52,12 +58,19 @@ export function separateOperations(
52
58
const dependencies = Object . create ( null ) ;
53
59
collectTransitiveDependencies ( dependencies , depGraph , operationName ) ;
54
60
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
+
55
71
separatedDocumentASTs [ operationName ] = {
56
72
kind : 'Document' ,
57
- definitions : documentAST . definitions . filter ( def =>
58
- def === operation ||
59
- def . kind === 'FragmentDefinition' && dependencies [ def . name . value ]
60
- )
73
+ definitions
61
74
} ;
62
75
} ) ;
63
76
0 commit comments