1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.separateOperations = separateOperations;
|
7 |
|
8 | var _visitor = require('../language/visitor');
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function separateOperations(documentAST) {
|
17 | var operations = [];
|
18 | var fragments = Object.create(null);
|
19 | var positions = new Map();
|
20 | var depGraph = Object.create(null);
|
21 | var fromName = void 0;
|
22 | var idx = 0;
|
23 |
|
24 |
|
25 | (0, _visitor.visit)(documentAST, {
|
26 | OperationDefinition: function OperationDefinition(node) {
|
27 | fromName = opName(node);
|
28 | operations.push(node);
|
29 | positions.set(node, idx++);
|
30 | },
|
31 | FragmentDefinition: function FragmentDefinition(node) {
|
32 | fromName = node.name.value;
|
33 | fragments[fromName] = node;
|
34 | positions.set(node, idx++);
|
35 | },
|
36 | FragmentSpread: function FragmentSpread(node) {
|
37 | var toName = node.name.value;
|
38 | (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true;
|
39 | }
|
40 | });
|
41 |
|
42 |
|
43 |
|
44 | var separatedDocumentASTs = Object.create(null);
|
45 | operations.forEach(function (operation) {
|
46 | var operationName = opName(operation);
|
47 | var dependencies = Object.create(null);
|
48 | collectTransitiveDependencies(dependencies, depGraph, operationName);
|
49 |
|
50 |
|
51 |
|
52 | var definitions = [operation];
|
53 | Object.keys(dependencies).forEach(function (name) {
|
54 | definitions.push(fragments[name]);
|
55 | });
|
56 | definitions.sort(function (n1, n2) {
|
57 | return (positions.get(n1) || 0) - (positions.get(n2) || 0);
|
58 | });
|
59 |
|
60 | separatedDocumentASTs[operationName] = {
|
61 | kind: 'Document',
|
62 | definitions: definitions
|
63 | };
|
64 | });
|
65 |
|
66 | return separatedDocumentASTs;
|
67 | } |
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | function opName(operation) {
|
78 | return operation.name ? operation.name.value : '';
|
79 | }
|
80 |
|
81 |
|
82 |
|
83 | function collectTransitiveDependencies(collected, depGraph, fromName) {
|
84 | var immediateDeps = depGraph[fromName];
|
85 | if (immediateDeps) {
|
86 | Object.keys(immediateDeps).forEach(function (toName) {
|
87 | if (!collected[toName]) {
|
88 | collected[toName] = true;
|
89 | collectTransitiveDependencies(collected, depGraph, toName);
|
90 | }
|
91 | });
|
92 | }
|
93 | } |
\ | No newline at end of file |