-
Notifications
You must be signed in to change notification settings - Fork 399
/
graphql-federation.factory.ts
272 lines (251 loc) · 8.71 KB
/
graphql-federation.factory.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
import { Injectable } from '@nestjs/common';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { isString } from '@nestjs/common/utils/shared.utils';
import { gql } from 'apollo-server-core';
import {
GraphQLAbstractType,
GraphQLField,
GraphQLInputField,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLResolveInfo,
GraphQLScalarType,
GraphQLSchema,
GraphQLUnionType,
isEnumType,
isInputObjectType,
isInterfaceType,
isObjectType,
isScalarType,
isUnionType,
} from 'graphql';
import { mergeSchemas } from '@graphql-tools/merge';
import { forEach, isEmpty } from 'lodash';
import { GraphQLSchemaBuilder } from '../graphql-schema.builder';
import { GqlModuleOptions } from '../interfaces';
import {
PluginsExplorerService,
ResolversExplorerService,
ScalarsExplorerService,
} from '../services';
import { extend } from '../utils';
import { transformSchema } from '../utils/transform-schema.util';
import { GraphQLSchemaHost } from '../graphql-schema.host';
@Injectable()
export class GraphQLFederationFactory {
constructor(
private readonly resolversExplorerService: ResolversExplorerService,
private readonly scalarsExplorerService: ScalarsExplorerService,
private readonly pluginsExplorerService: PluginsExplorerService,
private readonly gqlSchemaBuilder: GraphQLSchemaBuilder,
private readonly gqlSchemaHost: GraphQLSchemaHost,
) {}
async mergeOptions(
options: GqlModuleOptions = {},
): Promise<GqlModuleOptions> {
const transformSchema = async (schema) =>
options.transformSchema ? options.transformSchema(schema) : schema;
options.plugins = extend(
options.plugins || [],
this.pluginsExplorerService.explore(),
);
let schema: GraphQLSchema;
if (options.autoSchemaFile) {
schema = await this.generateSchema(options);
} else if (isEmpty(options.typeDefs)) {
schema = options.schema;
} else {
schema = this.buildSchemaFromTypeDefs(options);
}
this.gqlSchemaHost.schema = schema;
return {
...options,
schema: await transformSchema(schema),
typeDefs: undefined,
};
}
private buildSchemaFromTypeDefs(options: GqlModuleOptions) {
const { buildFederatedSchema } = loadPackage(
'@apollo/federation',
'ApolloFederation',
() => require('@apollo/federation'),
);
return buildFederatedSchema([
{
typeDefs: gql`
${options.typeDefs}
`,
resolvers: this.getResolvers(options.resolvers),
},
]);
}
private async generateSchema(
options: GqlModuleOptions,
): Promise<GraphQLSchema> {
const {
buildFederatedSchema,
printSchema,
} = loadPackage('@apollo/federation', 'ApolloFederation', () =>
require('@apollo/federation'),
);
const autoGeneratedSchema: GraphQLSchema = await this.gqlSchemaBuilder.buildFederatedSchema(
options.autoSchemaFile,
options,
this.resolversExplorerService.getAllCtors(),
);
let executableSchema: GraphQLSchema = buildFederatedSchema({
typeDefs: gql(printSchema(autoGeneratedSchema)),
resolvers: this.getResolvers(options.resolvers),
});
executableSchema = this.overrideOrExtendResolvers(
executableSchema,
autoGeneratedSchema,
);
const schema = options.schema
? mergeSchemas({
schemas: [options.schema, executableSchema],
})
: executableSchema;
return schema;
}
private getResolvers(optionResolvers: any) {
optionResolvers = Array.isArray(optionResolvers)
? optionResolvers
: [optionResolvers];
return this.extendResolvers([
this.resolversExplorerService.explore(),
...this.scalarsExplorerService.explore(),
...optionResolvers,
]);
}
private extendResolvers(resolvers: any[]) {
return resolvers.reduce((prev, curr) => extend(prev, curr), {});
}
private overrideOrExtendResolvers(
executableSchema: GraphQLSchema,
autoGeneratedSchema: GraphQLSchema,
): GraphQLSchema {
// Note: "transformSchema" from "apollo-graphql" cannot be used since it removes directives added by the "buildFederatedSchema" function
// Ref issue: https://github.com/apollographql/apollo-server/issues/4106
return transformSchema(executableSchema, (type) => {
if (isUnionType(type) && type.name !== '_Entity') {
return this.overrideFederatedResolveType(type, autoGeneratedSchema);
} else if (isInterfaceType(type)) {
return this.overrideFederatedResolveType(type, autoGeneratedSchema);
} else if (isEnumType(type)) {
return autoGeneratedSchema.getType(type.name);
} else if (isInputObjectType(type)) {
const autoGeneratedInputType = autoGeneratedSchema.getType(
type.name,
) as GraphQLInputObjectType;
if (!autoGeneratedInputType) {
return type;
}
const fields = type.getFields();
forEach(fields, (value: GraphQLInputField, key: string) => {
const field = autoGeneratedInputType.getFields()[key];
if (!field) {
return;
}
value.extensions = field.extensions;
value.astNode = field.astNode;
});
type.extensions = autoGeneratedInputType.extensions;
return type;
} else if (isObjectType(type)) {
const autoGeneratedObjectType = autoGeneratedSchema.getType(
type.name,
) as GraphQLObjectType;
if (!autoGeneratedObjectType) {
return type;
}
const fields = type.getFields();
forEach(
fields,
(value: GraphQLField<unknown, unknown>, key: string) => {
const field = autoGeneratedObjectType.getFields()[key];
if (!field) {
return;
}
value.extensions = field.extensions;
value.astNode = field.astNode;
if (!value.resolve) {
value.resolve = field.resolve;
}
},
);
type.extensions = autoGeneratedObjectType.extensions;
return type;
} else if (isScalarType(type) && type.name === 'DateTime') {
const autoGeneratedScalar = autoGeneratedSchema.getType(
type.name,
) as GraphQLScalarType;
if (!autoGeneratedScalar) {
return type;
}
type.parseLiteral = autoGeneratedScalar.parseLiteral;
type.parseValue = autoGeneratedScalar.parseValue;
return type;
}
return type;
});
}
/**
* Ensures that the resolveType method for unions and interfaces in the federated schema
* is properly set from the one in the autoGeneratedSchema.
*/
private overrideFederatedResolveType(
typeInFederatedSchema: GraphQLUnionType | GraphQLInterfaceType,
autoGeneratedSchema: GraphQLSchema,
): GraphQLUnionType | GraphQLInterfaceType {
// Get the matching type from the auto generated schema
const autoGeneratedType = autoGeneratedSchema.getType(
typeInFederatedSchema.name,
);
// Bail if inconsistent with original schema
if (
!autoGeneratedType ||
!(autoGeneratedType instanceof GraphQLUnionType || autoGeneratedType instanceof GraphQLInterfaceType) ||
!autoGeneratedType.resolveType
) {
return typeInFederatedSchema;
}
typeInFederatedSchema.resolveType = async (
value: unknown,
context: unknown,
info: GraphQLResolveInfo,
abstractType: GraphQLAbstractType,
) => {
const resultFromAutogenSchema = await autoGeneratedType.resolveType(
value,
context,
info,
abstractType,
);
// If the result is not a GraphQLObjectType we're fine
if (!resultFromAutogenSchema || isString(resultFromAutogenSchema)) {
return resultFromAutogenSchema;
}
// We now have a GraphQLObjectType from the original union in the autogenerated schema.
// But we can't return that without the additional federation property apollo adds to object
// types (see node_modules/@apollo/federation/src/composition/types.ts:47).
// Without that property, Apollo will ignore the returned type and the
// union value will resolve to null. So we need to return the type with
// the same name from the federated schema
const resultFromFederatedSchema = info.schema.getType(
resultFromAutogenSchema.name,
);
if (
resultFromFederatedSchema &&
resultFromFederatedSchema instanceof GraphQLObjectType
) {
return resultFromFederatedSchema;
}
// If we couldn't find a match in the federated schema, return just the
// name of the type and hope apollo works it out
return resultFromAutogenSchema.name;
};
return typeInFederatedSchema;
}
}