/
delegateToSchema.ts
228 lines (201 loc) · 6.36 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
import {
subscribe,
execute,
validate,
GraphQLSchema,
ExecutionResult,
isSchema,
FieldDefinitionNode,
getOperationAST,
OperationTypeNode,
OperationDefinitionNode,
DocumentNode,
GraphQLOutputType,
GraphQLObjectType,
} from 'graphql';
import { mapAsyncIterator, CombinedError, Transform } from '@graphql-tools/utils';
import {
IDelegateToSchemaOptions,
IDelegateRequestOptions,
SubschemaConfig,
ExecutionParams,
} from './types';
import { isSubschemaConfig } from './Subschema';
import { createRequestFromInfo, getDelegatingOperation } from './createRequest';
import { Transformer } from './Transformer';
export function delegateToSchema(options: IDelegateToSchemaOptions | GraphQLSchema): any {
if (isSchema(options)) {
throw new Error(
'Passing positional arguments to delegateToSchema is deprecated. ' + 'Please pass named parameters instead.'
);
}
const {
info,
operation = getDelegatingOperation(info.parentType, info.schema),
fieldName = info.fieldName,
returnType = info.returnType,
selectionSet,
fieldNodes,
} = options;
const request = createRequestFromInfo({
info,
operation,
fieldName,
selectionSet,
fieldNodes,
});
return delegateRequest({
...options,
request,
operation,
fieldName,
returnType,
});
}
function getDelegationReturnType(
targetSchema: GraphQLSchema,
operation: OperationTypeNode,
fieldName: string
): GraphQLOutputType {
let rootType: GraphQLObjectType<any, any>;
if (operation === 'query') {
rootType = targetSchema.getQueryType();
} else if (operation === 'mutation') {
rootType = targetSchema.getMutationType();
} else {
rootType = targetSchema.getSubscriptionType();
}
return rootType.getFields()[fieldName].type;
}
export function delegateRequest({
request,
schema: subschemaOrSubschemaConfig,
rootValue,
info,
operation,
fieldName,
args,
returnType,
context,
transforms = [],
transformedSchema,
skipValidation,
skipTypeMerging,
binding,
}: IDelegateRequestOptions) {
let operationDefinition: OperationDefinitionNode;
let targetOperation: OperationTypeNode;
let targetFieldName: string;
if (operation == null) {
operationDefinition = getOperationAST(request.document, undefined);
targetOperation = operationDefinition.operation;
} else {
targetOperation = operation;
}
if (fieldName == null) {
operationDefinition = operationDefinition ?? getOperationAST(request.document, undefined);
targetFieldName = ((operationDefinition.selectionSet.selections[0] as unknown) as FieldDefinitionNode).name.value;
} else {
targetFieldName = fieldName;
}
let targetSchema: GraphQLSchema;
let targetRootValue: Record<string, any>;
let subschemaConfig: SubschemaConfig;
let allTransforms: Array<Transform>;
if (isSubschemaConfig(subschemaOrSubschemaConfig)) {
subschemaConfig = subschemaOrSubschemaConfig;
targetSchema = subschemaConfig.schema;
targetRootValue = rootValue ?? subschemaConfig?.rootValue ?? info?.rootValue;
allTransforms =
subschemaOrSubschemaConfig.transforms != null
? subschemaOrSubschemaConfig.transforms.concat(transforms)
: transforms;
} else {
targetSchema = subschemaOrSubschemaConfig;
targetRootValue = rootValue ?? info?.rootValue;
allTransforms = transforms;
}
const delegationContext = {
subschema: subschemaOrSubschemaConfig,
targetSchema,
operation: targetOperation,
fieldName: targetFieldName,
args,
context,
info,
returnType:
returnType ?? info?.returnType ?? getDelegationReturnType(targetSchema, targetOperation, targetFieldName),
transforms: allTransforms,
transformedSchema: transformedSchema ?? targetSchema,
skipTypeMerging,
};
const transformer = new Transformer(delegationContext, binding);
const processedRequest = transformer.transformRequest(request);
if (!skipValidation) {
validateRequest(targetSchema, processedRequest.document);
}
if (targetOperation === 'query' || targetOperation === 'mutation') {
const executor =
subschemaConfig?.executor || createDefaultExecutor(targetSchema, subschemaConfig?.rootValue || targetRootValue);
const executionResult = executor({
document: processedRequest.document,
variables: processedRequest.variables,
context,
info,
});
if (executionResult instanceof Promise) {
return executionResult.then(originalResult => transformer.transformResult(originalResult));
}
return transformer.transformResult(executionResult);
}
const subscriber =
subschemaConfig?.subscriber || createDefaultSubscriber(targetSchema, subschemaConfig?.rootValue || targetRootValue);
return subscriber({
document: processedRequest.document,
variables: processedRequest.variables,
context,
info,
}).then((subscriptionResult: AsyncIterableIterator<ExecutionResult> | ExecutionResult) => {
if (Symbol.asyncIterator in subscriptionResult) {
// "subscribe" to the subscription result and map the result through the transforms
return mapAsyncIterator<ExecutionResult, any>(
subscriptionResult as AsyncIterableIterator<ExecutionResult>,
originalResult => ({
[targetFieldName]: transformer.transformResult(originalResult),
})
);
}
return transformer.transformResult(subscriptionResult as ExecutionResult);
});
}
function validateRequest(targetSchema: GraphQLSchema, document: DocumentNode) {
const errors = validate(targetSchema, document);
if (errors.length > 0) {
if (errors.length > 1) {
const combinedError = new CombinedError(errors);
throw combinedError;
}
const error = errors[0];
throw error.originalError || error;
}
}
function createDefaultExecutor(schema: GraphQLSchema, rootValue: Record<string, any>) {
return ({ document, context, variables, info }: ExecutionParams) =>
execute({
schema,
document,
contextValue: context,
variableValues: variables,
rootValue: rootValue ?? info?.rootValue,
});
}
function createDefaultSubscriber(schema: GraphQLSchema, rootValue: Record<string, any>) {
return ({ document, context, variables, info }: ExecutionParams) =>
subscribe({
schema,
document,
contextValue: context,
variableValues: variables,
rootValue: rootValue ?? info?.rootValue,
}) as any;
}