/
delegateToSchema.ts
238 lines (210 loc) · 6.64 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
import {
subscribe,
execute,
validate,
GraphQLSchema,
FieldDefinitionNode,
getOperationAST,
OperationTypeNode,
OperationDefinitionNode,
DocumentNode,
GraphQLOutputType,
ExecutionArgs,
} from 'graphql';
import { ValueOrPromise } from 'value-or-promise';
import { getBatchingExecutor } from '@graphql-tools/batch-execute';
import {
mapAsyncIterator,
Executor,
ExecutionRequest,
Maybe,
AggregateError,
isAsyncIterable,
getDefinedRootType,
} from '@graphql-tools/utils';
import {
IDelegateToSchemaOptions,
IDelegateRequestOptions,
StitchingInfo,
DelegationContext,
SubschemaConfig,
} from './types';
import { isSubschemaConfig } from './subschemaConfig';
import { Subschema } from './Subschema';
import { createRequestFromInfo, getDelegatingOperation } from './createRequest';
import { Transformer } from './Transformer';
export function delegateToSchema<TContext = Record<string, any>, TArgs = any>(
options: IDelegateToSchemaOptions<TContext, TArgs>
): any {
const {
info,
schema,
rootValue,
operationName,
operation = getDelegatingOperation(info.parentType, info.schema),
fieldName = info.fieldName,
selectionSet,
fieldNodes,
context,
} = options;
const request = createRequestFromInfo({
info,
operation,
fieldName,
selectionSet,
fieldNodes,
rootValue: rootValue ?? (schema as SubschemaConfig).rootValue,
operationName,
context,
});
return delegateRequest({
...options,
request,
});
}
function getDelegationReturnType(
targetSchema: GraphQLSchema,
operation: OperationTypeNode,
fieldName: string
): GraphQLOutputType {
const rootType = getDefinedRootType(targetSchema, operation);
return rootType.getFields()[fieldName].type;
}
export function delegateRequest<TContext = Record<string, any>, TArgs = any>(
options: IDelegateRequestOptions<TContext, TArgs>
) {
const delegationContext = getDelegationContext(options);
const transformer = new Transformer<TContext>(delegationContext);
const processedRequest = transformer.transformRequest(options.request);
if (options.validateRequest) {
validateRequest(delegationContext, processedRequest.document);
}
const executor = getExecutor(delegationContext);
return new ValueOrPromise(() => executor(processedRequest))
.then(originalResult => {
if (isAsyncIterable(originalResult)) {
// "subscribe" to the subscription result and map the result through the transforms
return mapAsyncIterator(originalResult, result => transformer.transformResult(result));
}
return transformer.transformResult(originalResult);
})
.resolve();
}
function getDelegationContext<TContext>({
request,
schema,
fieldName,
returnType,
args,
info,
transforms = [],
transformedSchema,
skipTypeMerging = false,
}: IDelegateRequestOptions<TContext>): DelegationContext<TContext> {
const { operationType: operation, context, operationName, document } = request;
let operationDefinition: Maybe<OperationDefinitionNode>;
let targetFieldName: string;
if (fieldName == null) {
operationDefinition = getOperationAST(document, operationName);
if (operationDefinition == null) {
throw new Error('Cannot infer main operation from the provided document.');
}
targetFieldName = (operationDefinition?.selectionSet.selections[0] as unknown as FieldDefinitionNode).name.value;
} else {
targetFieldName = fieldName;
}
const stitchingInfo: Maybe<StitchingInfo<TContext>> = info?.schema.extensions?.['stitchingInfo'];
const subschemaOrSubschemaConfig: GraphQLSchema | SubschemaConfig<any, any, any, any> =
stitchingInfo?.subschemaMap.get(schema) ?? schema;
if (isSubschemaConfig(subschemaOrSubschemaConfig)) {
const targetSchema = subschemaOrSubschemaConfig.schema;
return {
subschema: schema,
subschemaConfig: subschemaOrSubschemaConfig,
targetSchema,
operation,
fieldName: targetFieldName,
args,
context,
info,
returnType: returnType ?? info?.returnType ?? getDelegationReturnType(targetSchema, operation, targetFieldName),
transforms:
subschemaOrSubschemaConfig.transforms != null
? subschemaOrSubschemaConfig.transforms.concat(transforms)
: transforms,
transformedSchema:
transformedSchema ??
(subschemaOrSubschemaConfig instanceof Subschema ? subschemaOrSubschemaConfig.transformedSchema : targetSchema),
skipTypeMerging,
};
}
return {
subschema: schema,
subschemaConfig: undefined,
targetSchema: subschemaOrSubschemaConfig,
operation,
fieldName: targetFieldName,
args,
context,
info,
returnType:
returnType ?? info?.returnType ?? getDelegationReturnType(subschemaOrSubschemaConfig, operation, targetFieldName),
transforms,
transformedSchema: transformedSchema ?? subschemaOrSubschemaConfig,
skipTypeMerging,
};
}
function validateRequest(delegationContext: DelegationContext<any>, document: DocumentNode) {
const errors = validate(delegationContext.targetSchema, document);
if (errors.length > 0) {
if (errors.length > 1) {
const combinedError = new AggregateError(errors);
throw combinedError;
}
const error = errors[0];
throw error.originalError || error;
}
}
function getExecutor<TContext>(delegationContext: DelegationContext<TContext>): Executor<TContext> {
const { subschemaConfig, targetSchema, context } = delegationContext;
let executor: Executor = subschemaConfig?.executor || createDefaultExecutor(targetSchema);
if (subschemaConfig?.batch) {
const batchingOptions = subschemaConfig?.batchingOptions;
executor = getBatchingExecutor(
context ?? globalThis ?? window ?? global,
executor,
batchingOptions?.dataLoaderOptions,
batchingOptions?.extensionsReducer
);
}
return executor;
}
const defaultExecutorCache = new WeakMap<GraphQLSchema, Executor>();
function createDefaultExecutor(schema: GraphQLSchema): Executor {
let defaultExecutor = defaultExecutorCache.get(schema);
if (!defaultExecutor) {
defaultExecutor = function defaultExecutor({
document,
context,
variables,
rootValue,
operationName,
operationType,
}: ExecutionRequest) {
const executionArgs: ExecutionArgs = {
schema,
document,
contextValue: context,
variableValues: variables,
rootValue,
operationName,
};
if (operationType === 'subscription') {
return subscribe(executionArgs);
}
return execute(executionArgs);
} as Executor;
defaultExecutorCache.set(schema, defaultExecutor);
}
return defaultExecutor;
}