-
-
Notifications
You must be signed in to change notification settings - Fork 809
/
mergeExecutionParams.ts
285 lines (263 loc) · 8.32 KB
/
mergeExecutionParams.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// adapted from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js
import {
visit,
Kind,
DefinitionNode,
OperationDefinitionNode,
DocumentNode,
FragmentDefinitionNode,
VariableDefinitionNode,
SelectionNode,
FragmentSpreadNode,
VariableNode,
VisitorKeyMap,
ASTKindToNode,
InlineFragmentNode,
FieldNode,
OperationTypeNode,
} from 'graphql';
import { ExecutionParams } from './types';
import { createPrefix } from './prefix';
/**
* Merge multiple queries into a single query in such a way that query results
* can be split and transformed as if they were obtained by running original queries.
*
* Merging algorithm involves several transformations:
* 1. Replace top-level fragment spreads with inline fragments (... on Query {})
* 2. Add unique aliases to all top-level query fields (including those on inline fragments)
* 3. Prefix all variable definitions and variable usages
* 4. Prefix names (and spreads) of fragments
*
* i.e transform:
* [
* `query Foo($id: ID!) { foo, bar(id: $id), ...FooQuery }
* fragment FooQuery on Query { baz }`,
*
* `query Bar($id: ID!) { foo: baz, bar(id: $id), ... on Query { baz } }`
* ]
* to:
* query (
* $graphqlTools1_id: ID!
* $graphqlTools2_id: ID!
* ) {
* graphqlTools1_foo: foo,
* graphqlTools1_bar: bar(id: $graphqlTools1_id)
* ... on Query {
* graphqlTools1__baz: baz
* }
* graphqlTools1__foo: baz
* graphqlTools1__bar: bar(id: $graphqlTools1__id)
* ... on Query {
* graphqlTools1__baz: baz
* }
* }
*/
export function mergeExecutionParams(
execs: Array<ExecutionParams>,
extensionsReducer: (mergedExtensions: Record<string, any>, executionParams: ExecutionParams) => Record<string, any>
): ExecutionParams {
const mergedVariables: Record<string, any> = Object.create(null);
const mergedVariableDefinitions: Array<VariableDefinitionNode> = [];
const mergedSelections: Array<SelectionNode> = [];
const mergedFragmentDefinitions: Array<FragmentDefinitionNode> = [];
let mergedExtensions: Record<string, any> = Object.create(null);
let operation: OperationTypeNode;
execs.forEach((executionParams, index) => {
const prefixedExecutionParams = prefixExecutionParams(createPrefix(index), executionParams);
prefixedExecutionParams.document.definitions.forEach(def => {
if (isOperationDefinition(def)) {
operation = def.operation;
mergedSelections.push(...def.selectionSet.selections);
mergedVariableDefinitions.push(...(def.variableDefinitions ?? []));
}
if (isFragmentDefinition(def)) {
mergedFragmentDefinitions.push(def);
}
});
Object.assign(mergedVariables, prefixedExecutionParams.variables);
mergedExtensions = extensionsReducer(mergedExtensions, executionParams);
});
const mergedOperationDefinition: OperationDefinitionNode = {
kind: Kind.OPERATION_DEFINITION,
operation,
variableDefinitions: mergedVariableDefinitions,
selectionSet: {
kind: Kind.SELECTION_SET,
selections: mergedSelections,
},
};
return {
document: {
kind: Kind.DOCUMENT,
definitions: [mergedOperationDefinition, ...mergedFragmentDefinitions],
},
variables: mergedVariables,
extensions: mergedExtensions,
context: execs[0].context,
info: execs[0].info,
};
}
function prefixExecutionParams(prefix: string, executionParams: ExecutionParams): ExecutionParams {
let document = aliasTopLevelFields(prefix, executionParams.document);
const variableNames = Object.keys(executionParams.variables);
if (variableNames.length === 0) {
return { ...executionParams, document };
}
document = visit(document, {
[Kind.VARIABLE]: (node: VariableNode) => prefixNodeName(node, prefix),
[Kind.FRAGMENT_DEFINITION]: (node: FragmentDefinitionNode) => prefixNodeName(node, prefix),
[Kind.FRAGMENT_SPREAD]: (node: FragmentSpreadNode) => prefixNodeName(node, prefix),
});
const prefixedVariables = variableNames.reduce((acc, name) => {
acc[prefix + name] = executionParams.variables[name];
return acc;
}, Object.create(null));
return {
document,
variables: prefixedVariables,
};
}
/**
* Adds prefixed aliases to top-level fields of the query.
*
* @see aliasFieldsInSelection for implementation details
*/
function aliasTopLevelFields(prefix: string, document: DocumentNode): DocumentNode {
const transformer = {
[Kind.OPERATION_DEFINITION]: (def: OperationDefinitionNode) => {
const { selections } = def.selectionSet;
return {
...def,
selectionSet: {
...def.selectionSet,
selections: aliasFieldsInSelection(prefix, selections, document),
},
};
},
};
return visit(document, transformer, ({ [Kind.DOCUMENT]: [`definitions`] } as unknown) as VisitorKeyMap<
ASTKindToNode
>);
}
/**
* Add aliases to fields of the selection, including top-level fields of inline fragments.
* Fragment spreads are converted to inline fragments and their top-level fields are also aliased.
*
* Note that this method is shallow. It adds aliases only to the top-level fields and doesn't
* descend to field sub-selections.
*
* For example, transforms:
* {
* foo
* ... on Query { foo }
* ...FragmentWithBarField
* }
* To:
* {
* graphqlTools1_foo: foo
* ... on Query { graphqlTools1_foo: foo }
* ... on Query { graphqlTools1_bar: bar }
* }
*/
function aliasFieldsInSelection(
prefix: string,
selections: ReadonlyArray<SelectionNode>,
document: DocumentNode
): Array<SelectionNode> {
return selections.map(selection => {
switch (selection.kind) {
case Kind.INLINE_FRAGMENT:
return aliasFieldsInInlineFragment(prefix, selection, document);
case Kind.FRAGMENT_SPREAD: {
const inlineFragment = inlineFragmentSpread(selection, document);
return aliasFieldsInInlineFragment(prefix, inlineFragment, document);
}
case Kind.FIELD:
default:
return aliasField(selection, prefix);
}
});
}
/**
* Add aliases to top-level fields of the inline fragment.
* Returns new inline fragment node.
*
* For Example, transforms:
* ... on Query { foo, ... on Query { bar: foo } }
* To
* ... on Query { graphqlTools1_foo: foo, ... on Query { graphqlTools1_bar: foo } }
*/
function aliasFieldsInInlineFragment(
prefix: string,
fragment: InlineFragmentNode,
document: DocumentNode
): InlineFragmentNode {
const { selections } = fragment.selectionSet;
return {
...fragment,
selectionSet: {
...fragment.selectionSet,
selections: aliasFieldsInSelection(prefix, selections, document),
},
};
}
/**
* Replaces fragment spread with inline fragment
*
* Example:
* query { ...Spread }
* fragment Spread on Query { bar }
*
* Transforms to:
* query { ... on Query { bar } }
*/
function inlineFragmentSpread(spread: FragmentSpreadNode, document: DocumentNode): InlineFragmentNode {
const fragment = document.definitions.find(
def => isFragmentDefinition(def) && def.name.value === spread.name.value
) as FragmentDefinitionNode;
if (!fragment) {
throw new Error(`Fragment ${spread.name.value} does not exist`);
}
const { typeCondition, selectionSet } = fragment;
return {
kind: Kind.INLINE_FRAGMENT,
typeCondition,
selectionSet,
directives: spread.directives,
};
}
function prefixNodeName<T extends VariableNode | FragmentDefinitionNode | FragmentSpreadNode>(
namedNode: T,
prefix: string
): T {
return {
...namedNode,
name: {
...namedNode.name,
value: prefix + namedNode.name.value,
},
};
}
/**
* Returns a new FieldNode with prefixed alias
*
* Example. Given prefix === "graphqlTools1_" transforms:
* { foo } -> { graphqlTools1_foo: foo }
* { foo: bar } -> { graphqlTools1_foo: bar }
*/
function aliasField(field: FieldNode, aliasPrefix: string): FieldNode {
const aliasNode = field.alias ? field.alias : field.name;
return {
...field,
alias: {
...aliasNode,
value: aliasPrefix + aliasNode.value,
},
};
}
function isOperationDefinition(def: DefinitionNode): def is OperationDefinitionNode {
return def.kind === Kind.OPERATION_DEFINITION;
}
function isFragmentDefinition(def: DefinitionNode): def is FragmentDefinitionNode {
return def.kind === Kind.FRAGMENT_DEFINITION;
}