forked from nestjs/graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphql.module.ts
More file actions
267 lines (242 loc) · 7.82 KB
/
graphql.module.ts
File metadata and controls
267 lines (242 loc) · 7.82 KB
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
import { Inject, Module } from '@nestjs/common';
import {
DynamicModule,
OnModuleDestroy,
OnModuleInit,
Provider,
} from '@nestjs/common/interfaces';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { ApplicationConfig, HttpAdapterHost } from '@nestjs/core';
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import { ApolloServerBase } from 'apollo-server-core';
import { printSchema } from '@apollo/federation';
import { GraphQLAstExplorer } from './graphql-ast.explorer';
import { GraphQLSchemaBuilder } from './graphql-schema.builder';
import { GraphQLSchemaHost } from './graphql-schema.host';
import { GraphQLTypesLoader } from './graphql-types.loader';
import { GraphQLSubscriptionService } from './graphql-ws/graphql-subscription.service';
import { GRAPHQL_MODULE_ID, GRAPHQL_MODULE_OPTIONS } from './graphql.constants';
import { GraphQLFactory } from './graphql.factory';
import {
GqlModuleAsyncOptions,
GqlModuleOptions,
GqlOptionsFactory,
SubscriptionConfig,
} from './interfaces/gql-module-options.interface';
import { GraphQLSchemaBuilderModule } from './schema-builder/schema-builder.module';
import {
PluginsExplorerService,
ResolversExplorerService,
ScalarsExplorerService,
} from './services';
import {
extend,
generateString,
mergeDefaults,
normalizeRoutePath,
} from './utils';
@Module({
imports: [GraphQLSchemaBuilderModule],
providers: [
GraphQLFactory,
MetadataScanner,
ResolversExplorerService,
ScalarsExplorerService,
PluginsExplorerService,
GraphQLAstExplorer,
GraphQLTypesLoader,
GraphQLSchemaBuilder,
GraphQLSchemaHost,
],
exports: [GraphQLTypesLoader, GraphQLAstExplorer, GraphQLSchemaHost],
})
export class GraphQLModule implements OnModuleInit, OnModuleDestroy {
private _apolloServer: ApolloServerBase;
private _subscriptionService?: GraphQLSubscriptionService;
get apolloServer(): ApolloServerBase {
return this._apolloServer;
}
constructor(
private readonly httpAdapterHost: HttpAdapterHost,
@Inject(GRAPHQL_MODULE_OPTIONS) private readonly options: GqlModuleOptions,
private readonly graphqlFactory: GraphQLFactory,
private readonly graphqlTypesLoader: GraphQLTypesLoader,
private readonly applicationConfig: ApplicationConfig,
) {}
static forRoot(options: GqlModuleOptions = {}): DynamicModule {
options = mergeDefaults(options);
return {
module: GraphQLModule,
providers: [
{
provide: GRAPHQL_MODULE_OPTIONS,
useValue: options,
},
],
};
}
static forRootAsync(options: GqlModuleAsyncOptions): DynamicModule {
return {
module: GraphQLModule,
imports: options.imports,
providers: [
...this.createAsyncProviders(options),
{
provide: GRAPHQL_MODULE_ID,
useValue: generateString(),
},
],
};
}
private static createAsyncProviders(
options: GqlModuleAsyncOptions,
): Provider[] {
if (options.useExisting || options.useFactory) {
return [this.createAsyncOptionsProvider(options)];
}
return [
this.createAsyncOptionsProvider(options),
{
provide: options.useClass,
useClass: options.useClass,
},
];
}
private static createAsyncOptionsProvider(
options: GqlModuleAsyncOptions,
): Provider {
if (options.useFactory) {
return {
provide: GRAPHQL_MODULE_OPTIONS,
useFactory: async (...args: any[]) =>
mergeDefaults(await options.useFactory(...args)),
inject: options.inject || [],
};
}
return {
provide: GRAPHQL_MODULE_OPTIONS,
useFactory: async (optionsFactory: GqlOptionsFactory) =>
mergeDefaults(await optionsFactory.createGqlOptions()),
inject: [options.useExisting || options.useClass],
};
}
async onModuleInit() {
if (!this.httpAdapterHost) {
return;
}
const httpAdapter = this.httpAdapterHost.httpAdapter;
if (!httpAdapter) {
return;
}
const typeDefs =
(await this.graphqlTypesLoader.mergeTypesByPaths(
this.options.typePaths,
)) || [];
const mergedTypeDefs = extend(typeDefs, this.options.typeDefs);
const apolloOptions = await this.graphqlFactory.mergeOptions({
...this.options,
typeDefs: mergedTypeDefs,
});
await this.runExecutorFactoryIfPresent(apolloOptions);
if (this.options.definitions && this.options.definitions.path) {
await this.graphqlFactory.generateDefinitions(
printSchema(apolloOptions.schema),
this.options,
);
}
await this.registerGqlServer(apolloOptions);
if (
this.options.installSubscriptionHandlers ||
this.options.subscriptions
) {
const subscriptionsOptions: SubscriptionConfig = this.options
.subscriptions || { 'subscriptions-transport-ws': {} };
this._subscriptionService = new GraphQLSubscriptionService(
{
schema: apolloOptions.schema,
path: this.options.path,
context: this.options.context,
...subscriptionsOptions,
},
httpAdapter.getHttpServer(),
);
}
}
async onModuleDestroy() {
await this._subscriptionService?.stop();
await this._apolloServer?.stop();
}
private async registerGqlServer(apolloOptions: GqlModuleOptions) {
const httpAdapter = this.httpAdapterHost.httpAdapter;
const platformName = httpAdapter.getType();
if (platformName === 'express') {
await this.registerExpress(apolloOptions);
} else if (platformName === 'fastify') {
await this.registerFastify(apolloOptions);
} else {
throw new Error(`No support for current HttpAdapter: ${platformName}`);
}
}
private async registerExpress(apolloOptions: GqlModuleOptions) {
const { ApolloServer } = loadPackage(
'apollo-server-express',
'GraphQLModule',
() => require('apollo-server-express'),
);
const path = this.getNormalizedPath(apolloOptions);
const { disableHealthCheck, onHealthCheck, cors, bodyParserConfig } =
this.options;
const httpAdapter = this.httpAdapterHost.httpAdapter;
const app = httpAdapter.getInstance();
const apolloServer = new ApolloServer(apolloOptions as any);
await apolloServer.start();
apolloServer.applyMiddleware({
app,
path,
disableHealthCheck,
onHealthCheck,
cors,
bodyParserConfig,
});
this._apolloServer = apolloServer;
}
private async registerFastify(apolloOptions: GqlModuleOptions) {
const { ApolloServer } = loadPackage(
'apollo-server-fastify',
'GraphQLModule',
() => require('apollo-server-fastify'),
);
const httpAdapter = this.httpAdapterHost.httpAdapter;
const app = httpAdapter.getInstance();
const path = this.getNormalizedPath(apolloOptions);
const apolloServer = new ApolloServer(apolloOptions as any);
await apolloServer.start();
const { disableHealthCheck, onHealthCheck, cors, bodyParserConfig } =
this.options;
await app.register(
apolloServer.createHandler({
disableHealthCheck,
onHealthCheck,
cors,
bodyParserConfig,
path,
}),
);
this._apolloServer = apolloServer;
}
private getNormalizedPath(apolloOptions: GqlModuleOptions): string {
const prefix = this.applicationConfig.getGlobalPrefix();
const useGlobalPrefix = prefix && this.options.useGlobalPrefix;
const gqlOptionsPath = normalizeRoutePath(apolloOptions.path);
return useGlobalPrefix
? normalizeRoutePath(prefix) + gqlOptionsPath
: gqlOptionsPath;
}
private async runExecutorFactoryIfPresent(apolloOptions: GqlModuleOptions) {
if (!apolloOptions.executorFactory) {
return;
}
const executor = await apolloOptions.executorFactory(apolloOptions.schema);
apolloOptions.executor = executor;
}
}