This repository has been archived by the owner on Apr 15, 2020. It is now read-only.
forked from ardatan/graphql-tools
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdelegateToSchema.ts
302 lines (268 loc) · 7.97 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
import {
ArgumentNode,
DocumentNode,
FieldNode,
FragmentDefinitionNode,
Kind,
OperationDefinitionNode,
SelectionSetNode,
SelectionNode,
subscribe,
execute,
validate,
VariableDefinitionNode,
GraphQLSchema,
ExecutionResult,
NameNode,
} from 'graphql';
import {
IDelegateToSchemaOptions,
Operation,
Request,
Fetcher,
Delegator,
SubschemaConfig,
isSubschemaConfig,
} 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';
export default function delegateToSchema(
options: IDelegateToSchemaOptions | GraphQLSchema,
...args: any[]
): Promise<any> {
if (options instanceof GraphQLSchema) {
throw new Error(
'Passing positional arguments to delegateToSchema is a deprecated. ' +
'Please pass named parameters instead.',
);
}
return delegateToSchemaImplementation(options);
}
async function delegateToSchemaImplementation({
schema: subschema,
rootValue,
info,
operation = info.operation.operation,
fieldName,
args,
context,
transforms = [],
skipValidation,
}: IDelegateToSchemaOptions,
): Promise<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;
}
const rawDocument: DocumentNode = createDocument(
fieldName,
operation,
info.fieldNodes,
Object.keys(info.fragments).map(
fragmentName => info.fragments[fragmentName],
),
info.operation.variableDefinitions,
info.operation.name,
);
const rawRequest: Request = {
document: rawDocument,
variables: info.variableValues as Record<string, any>,
};
transforms = [
new CheckResultAndHandleErrors(info, fieldName, subschema, context),
...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)
);
}
transforms = transforms.concat([
new FilterToSchema(targetSchema),
new AddTypenameToAbstract(targetSchema),
]);
const processedRequest = applyRequestTransforms(rawRequest, transforms);
if (!skipValidation) {
const errors = validate(targetSchema, processedRequest.document);
if (errors.length > 0) {
throw errors;
}
}
if (operation === 'query' || operation === 'mutation') {
const executor = createExecutor(targetSchema, rootValue, subSchemaConfig);
return applyResultTransforms(
await executor({
document: processedRequest.document,
context,
variables: processedRequest.variables
}),
transforms,
);
} else if (operation === 'subscription') {
const subscriber = createSubscriber(targetSchema, rootValue, subSchemaConfig);
const originalAsyncIterator = (await subscriber({
document: processedRequest.document,
context,
variables: processedRequest.variables,
})) as AsyncIterator<ExecutionResult>;
// "subscribe" to the subscription result and map the result through the transforms
return mapAsyncIterator<ExecutionResult, any>(originalAsyncIterator, 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,
};
});
}
}
function createDocument(
targetField: string,
targetOperation: Operation,
originalSelections: ReadonlyArray<SelectionNode>,
fragments: Array<FragmentDefinitionNode>,
variables: ReadonlyArray<VariableDefinitionNode>,
operationName: NameNode,
): DocumentNode {
let selections: Array<SelectionNode> = [];
let args: Array<ArgumentNode> = [];
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: variables,
selectionSet: rootSelectionSet,
name: operationName,
};
return {
kind: Kind.DOCUMENT,
definitions: [operationDefinition, ...fragments],
};
}
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,
});
}
}