-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
Copy pathnest-factory.ts
253 lines (232 loc) · 8.04 KB
/
nest-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
import {
HttpServer,
INestApplication,
INestApplicationContext,
INestMicroservice,
} from '@nestjs/common';
import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface';
import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import { Logger } from '@nestjs/common/services/logger.service';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { isFunction, isNil } from '@nestjs/common/utils/shared.utils';
import { AbstractHttpAdapter } from './adapters/http-adapter';
import { ApplicationConfig } from './application-config';
import { MESSAGES } from './constants';
import { ExceptionsZone } from './errors/exceptions-zone';
import { loadAdapter } from './helpers/load-adapter';
import { NestContainer } from './injector/container';
import { InstanceLoader } from './injector/instance-loader';
import { MetadataScanner } from './metadata-scanner';
import { NestApplication } from './nest-application';
import { NestApplicationContext } from './nest-application-context';
import { DependenciesScanner } from './scanner';
/**
* @publicApi
*/
export class NestFactoryStatic {
private readonly logger = new Logger('NestFactory', true);
/**
* Creates an instance of NestApplication.
*
* @param module Entry (root) application module class
* @param options List of options to initialize NestApplication
*
* @returns A promise that, when resolved,
* contains a reference to the NestApplication instance.
*/
public async create<T extends INestApplication = INestApplication>(
module: any,
options?: NestApplicationOptions,
): Promise<T>;
/**
* Creates an instance of NestApplication with the specified `httpAdapter`.
*
* @param module Entry (root) application module class
* @param httpAdapter Adapter to proxy the request/response cycle to
* the underlying HTTP server
* @param options List of options to initialize NestApplication
*
* @returns A promise that, when resolved,
* contains a reference to the NestApplication instance.
*/
public async create<T extends INestApplication = INestApplication>(
module: any,
httpAdapter: AbstractHttpAdapter,
options?: NestApplicationOptions,
): Promise<T>;
public async create<T extends INestApplication = INestApplication>(
module: any,
serverOrOptions?: AbstractHttpAdapter | NestApplicationOptions,
options?: NestApplicationOptions,
): Promise<T> {
const [httpServer, appOptions] = this.isHttpServer(serverOrOptions)
? [serverOrOptions, options]
: [this.createHttpAdapter(), serverOrOptions];
const applicationConfig = new ApplicationConfig();
const container = new NestContainer(applicationConfig);
this.applyLogger(appOptions);
await this.initialize(module, container, applicationConfig, httpServer);
const instance = new NestApplication(
container,
httpServer,
applicationConfig,
appOptions,
);
const target = this.createNestInstance(instance);
return this.createAdapterProxy<T>(target, httpServer);
}
/**
* Creates an instance of NestMicroservice.
*
* @param module Entry (root) application module class
* @param options Optional microservice configuration
*
* @returns A promise that, when resolved,
* contains a reference to the NestMicroservice instance.
*/
public async createMicroservice<T extends object>(
module: any,
options?: NestMicroserviceOptions & T,
): Promise<INestMicroservice> {
const { NestMicroservice } = loadPackage(
'@nestjs/microservices',
'NestFactory',
() => require('@nestjs/microservices'),
);
const applicationConfig = new ApplicationConfig();
const container = new NestContainer(applicationConfig);
this.applyLogger(options);
await this.initialize(module, container, applicationConfig);
return this.createNestInstance<INestMicroservice>(
new NestMicroservice(container, options, applicationConfig),
);
}
/**
* Creates an instance of NestApplicationContext.
*
* @param module Entry (root) application module class
* @param options Optional Nest application configuration
*
* @returns A promise that, when resolved,
* contains a reference to the NestApplicationContext instance.
*/
public async createApplicationContext(
module: any,
options?: NestApplicationContextOptions,
): Promise<INestApplicationContext> {
const container = new NestContainer();
this.applyLogger(options);
await this.initialize(module, container);
const modules = container.getModules().values();
const root = modules.next().value;
const context = this.createNestInstance<NestApplicationContext>(
new NestApplicationContext(container, [], root),
);
return context.init();
}
private createNestInstance<T>(instance: T): T {
return this.createProxy(instance);
}
private async initialize(
module: any,
container: NestContainer,
config = new ApplicationConfig(),
httpServer: HttpServer = null,
) {
const instanceLoader = new InstanceLoader(container);
const metadataScanner = new MetadataScanner();
const dependenciesScanner = new DependenciesScanner(
container,
metadataScanner,
config,
);
container.setHttpAdapter(httpServer);
await httpServer?.init();
try {
this.logger.log(MESSAGES.APPLICATION_START);
await ExceptionsZone.asyncRun(async () => {
await dependenciesScanner.scan(module);
await instanceLoader.createInstancesOfDependencies();
dependenciesScanner.applyApplicationProviders();
});
} catch (e) {
process.abort();
}
}
private createProxy(target: any) {
const proxy = this.createExceptionProxy();
return new Proxy(target, {
get: proxy,
set: proxy,
});
}
private createExceptionProxy() {
return (receiver: Record<string, any>, prop: string) => {
if (!(prop in receiver)) {
return;
}
if (isFunction(receiver[prop])) {
return this.createExceptionZone(receiver, prop);
}
return receiver[prop];
};
}
private createExceptionZone(
receiver: Record<string, any>,
prop: string,
): Function {
return (...args: unknown[]) => {
let result: unknown;
ExceptionsZone.run(() => {
result = receiver[prop](...args);
});
return result;
};
}
private applyLogger(options: NestApplicationContextOptions | undefined) {
if (!options) {
return;
}
!isNil(options.logger) && Logger.overrideLogger(options.logger);
}
private createHttpAdapter<T = any>(httpServer?: T): AbstractHttpAdapter {
const { ExpressAdapter } = loadAdapter(
'@nestjs/platform-express',
'HTTP',
() => require('@nestjs/platform-express'),
);
return new ExpressAdapter(httpServer);
}
private isHttpServer(
serverOrOptions: AbstractHttpAdapter | NestApplicationOptions,
): serverOrOptions is AbstractHttpAdapter {
return !!(
serverOrOptions && (serverOrOptions as AbstractHttpAdapter).patch
);
}
private createAdapterProxy<T>(app: NestApplication, adapter: HttpServer): T {
return (new Proxy(app, {
get: (receiver: Record<string, any>, prop: string) => {
if (!(prop in receiver) && prop in adapter) {
return this.createExceptionZone(adapter, prop);
}
return receiver[prop];
},
}) as unknown) as T;
}
}
/**
* Use NestFactory to create an application instance.
*
* ### Specifying an entry module
*
* Pass the required *root module* for the application via the module parameter.
* By convention, it is usually called `ApplicationModule`. Starting with this
* module, Nest assembles the dependency graph and begins the process of
* Dependency Injection and instantiates the classes needed to launch your
* application.
*
* @publicApi
*/
export const NestFactory = new NestFactoryStatic();