This repository has been archived by the owner on Apr 15, 2020. It is now read-only.
forked from ardatan/graphql-tools
/
delegateToSchema.ts
371 lines (324 loc) · 9.57 KB
/
delegateToSchema.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import {
ArgumentNode,
FieldNode,
FragmentDefinitionNode,
Kind,
OperationDefinitionNode,
SelectionSetNode,
SelectionNode,
subscribe,
execute,
validate,
GraphQLSchema,
ExecutionResult,
} from 'graphql';
import {
IDelegateToSchemaOptions,
ICreateDelegatingRequestOptions,
IDelegateRequestOptions,
Operation,
Request,
Fetcher,
Delegator,
SubschemaConfig,
isSubschemaConfig,
IGraphQLToolsResolveInfo,
} from '../Interfaces';
import {
applyRequestTransforms,
applyResultTransforms,
} from '../transforms/transforms';
import AddArgumentsAsVariables from '../transforms/AddArgumentsAsVariables';
import FilterToSchema from '../transforms/FilterToSchema';
import AddTypenameToAbstract from '../transforms/AddTypenameToAbstract';
import CheckResultAndHandleErrors from '../transforms/CheckResultAndHandleErrors';
import mapAsyncIterator from './mapAsyncIterator';
import ExpandAbstractTypes from '../transforms/ExpandAbstractTypes';
import AddReplacementFragments from '../transforms/AddReplacementFragments';
import { ApolloLink, execute as executeLink } from 'apollo-link';
import linkToFetcher from './linkToFetcher';
import { observableToAsyncIterable } from './observableToAsyncIterable';
import { AddMergedTypeFragments } from '../transforms';
import { isAsyncIterable } from 'iterall';
export default function delegateToSchema(
options: IDelegateToSchemaOptions | GraphQLSchema,
): any {
if (options instanceof GraphQLSchema) {
throw new Error(
'Passing positional arguments to delegateToSchema is a deprecated. ' +
'Please pass named parameters instead.',
);
}
const {
schema: subschema,
rootValue,
info,
operation = info.operation.operation,
fieldName,
returnType = info.returnType,
args,
context,
transforms = [],
skipValidation,
} = options;
const request = createDelegatingRequest({
schema: subschema,
info,
operation,
fieldName,
args,
transforms,
skipValidation,
});
return delegateRequest({
request,
schema: subschema,
rootValue,
info,
operation,
fieldName,
returnType,
context,
transforms,
});
}
export function createDelegatingRequest({
schema: subschema,
info,
operation = info.operation.operation,
fieldName,
args,
transforms = [],
skipValidation,
}: ICreateDelegatingRequestOptions): any {
let targetSchema: GraphQLSchema;
let subschemaConfig: SubschemaConfig;
if (isSubschemaConfig(subschema)) {
subschemaConfig = subschema;
targetSchema = subschemaConfig.schema;
transforms = transforms.concat((subschemaConfig.transforms || []).slice().reverse());
} else {
targetSchema = subschema;
}
const initialRequest = createInitialRequest(fieldName, operation, info);
transforms = [
...transforms,
new ExpandAbstractTypes(info.schema, targetSchema),
];
if (info.mergeInfo) {
transforms.push(
new AddReplacementFragments(targetSchema, info.mergeInfo.replacementFragments),
new AddMergedTypeFragments(targetSchema, info.mergeInfo.mergedTypes),
);
}
if (args) {
transforms.push(
new AddArgumentsAsVariables(targetSchema, args, info.schema)
);
} else {
console.warn(
'"args" undefined. "args" argument may be required in a future version. Custom scalars or enums may not be properly serialized prior to delegation.'
);
}
transforms.push(
new FilterToSchema(targetSchema),
new AddTypenameToAbstract(targetSchema),
);
const delegatingRequest = applyRequestTransforms(initialRequest, transforms);
if (!skipValidation) {
const errors = validate(targetSchema, delegatingRequest.document);
if (errors.length > 0) {
throw errors;
}
}
return delegatingRequest;
}
export function delegateRequest({
request,
schema: subschema,
rootValue,
info,
operation = info.operation.operation,
fieldName,
returnType = info.returnType,
context,
transforms = [],
}: IDelegateRequestOptions): any {
let targetSchema: GraphQLSchema;
let subschemaConfig: SubschemaConfig;
if (isSubschemaConfig(subschema)) {
subschemaConfig = subschema;
targetSchema = subschemaConfig.schema;
rootValue = rootValue || subschemaConfig.rootValue || info.rootValue;
transforms = transforms.concat((subschemaConfig.transforms || []).slice().reverse());
} else {
targetSchema = subschema;
rootValue = rootValue || info.rootValue;
}
transforms = [
new CheckResultAndHandleErrors(info, fieldName, subschema, context, returnType),
...transforms,
];
if (operation === 'query' || operation === 'mutation') {
const executor = createExecutor(targetSchema, rootValue, subschemaConfig);
const executionResult: ExecutionResult | Promise<ExecutionResult> = executor({
document: request.document,
context,
variables: request.variables
});
if (executionResult instanceof Promise) {
return executionResult.then((originalResult: any) => applyResultTransforms(originalResult, transforms));
} else {
return applyResultTransforms(executionResult, transforms);
}
} else if (operation === 'subscription') {
const subscriber = createSubscriber(targetSchema, rootValue, subschemaConfig);
return subscriber({
document: request.document,
context,
variables: request.variables,
}).then((subscriptionResult: AsyncIterableIterator<ExecutionResult> | ExecutionResult) => {
if (isAsyncIterable(subscriptionResult)) {
// "subscribe" to the subscription result and map the result through the transforms
return mapAsyncIterator<ExecutionResult, any>(subscriptionResult, result => {
const transformedResult = applyResultTransforms(result, transforms);
// wrap with fieldName to return for an additional round of resolutioon
// with payload as rootValue
return {
[info.fieldName]: transformedResult,
};
});
} else {
return applyResultTransforms(subscriptionResult, transforms);
}
});
}
}
function createInitialRequest(
targetField: string,
targetOperation: Operation,
info: IGraphQLToolsResolveInfo,
): Request {
let selections: Array<SelectionNode> = [];
let args: Array<ArgumentNode> = [];
const originalSelections: ReadonlyArray<SelectionNode> = info.fieldNodes;
originalSelections.forEach((field: FieldNode) => {
const fieldSelections = field.selectionSet
? field.selectionSet.selections
: [];
selections = selections.concat(fieldSelections);
args = args.concat(field.arguments || []);
});
let selectionSet = null;
if (selections.length > 0) {
selectionSet = {
kind: Kind.SELECTION_SET,
selections: selections,
};
}
const rootField: FieldNode = {
kind: Kind.FIELD,
alias: null,
arguments: args,
selectionSet,
name: {
kind: Kind.NAME,
value: targetField,
},
};
const rootSelectionSet: SelectionSetNode = {
kind: Kind.SELECTION_SET,
selections: [rootField],
};
const operationDefinition: OperationDefinitionNode = {
kind: Kind.OPERATION_DEFINITION,
operation: targetOperation,
variableDefinitions: info.operation.variableDefinitions,
selectionSet: rootSelectionSet,
name: info.operation.name,
};
const fragments: Array<FragmentDefinitionNode> = Object.keys(info.fragments).map(
fragmentName => info.fragments[fragmentName],
);
const document = {
kind: Kind.DOCUMENT,
definitions: [operationDefinition, ...fragments],
};
return {
document,
variables: info.variableValues,
};
}
function createExecutor(
schema: GraphQLSchema,
rootValue: Record<string, any>,
subschemaConfig?: SubschemaConfig
): Delegator {
let fetcher: Fetcher;
if (subschemaConfig) {
if (subschemaConfig.dispatcher) {
const dynamicLinkOrFetcher = subschemaConfig.dispatcher(context);
fetcher = (typeof dynamicLinkOrFetcher === 'function') ?
dynamicLinkOrFetcher :
linkToFetcher(dynamicLinkOrFetcher);
} else if (subschemaConfig.link) {
fetcher = linkToFetcher(subschemaConfig.link);
} else if (subschemaConfig.fetcher) {
fetcher = subschemaConfig.fetcher;
}
if (!fetcher && !rootValue && subschemaConfig.rootValue) {
rootValue = subschemaConfig.rootValue;
}
}
if (fetcher) {
return ({ document, context, variables }) => fetcher({
query: document,
variables,
context: { graphqlContext: context }
});
} else {
return ({ document, context, variables }) => execute({
schema,
document,
rootValue,
contextValue: context,
variableValues: variables,
});
}
}
function createSubscriber(
schema: GraphQLSchema,
rootValue: Record<string, any>,
subschemaConfig?: SubschemaConfig
): Delegator {
let link: ApolloLink;
if (subschemaConfig) {
if (subschemaConfig.dispatcher) {
link = subschemaConfig.dispatcher(context) as ApolloLink;
} else if (subschemaConfig.link) {
link = subschemaConfig.link;
}
if (!link && !rootValue && subschemaConfig.rootValue) {
rootValue = subschemaConfig.rootValue;
}
}
if (link) {
return ({ document, context, variables }) => {
const operation = {
query: document,
variables,
context: { graphqlContext: context }
};
const observable = executeLink(link, operation);
return observableToAsyncIterable(observable);
};
} else {
return ({ document, context, variables }) => subscribe({
schema,
document,
rootValue,
contextValue: context,
variableValues: variables,
});
}
}