-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
PlatformBuilder.ts
254 lines (207 loc) · 6.25 KB
/
PlatformBuilder.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
import {classOf, constructorOf, Type} from "@tsed/core";
import {InjectorService} from "@tsed/di";
import {
GlobalAcceptMimesMiddleware,
IRoute,
LogIncomingRequestMiddleware,
Platform,
PlatformApplication,
PlatformContextMiddleware
} from "../../platform";
import {GlobalErrorHandlerMiddleware, PlatformExceptionsMiddleware} from "../../platform-exceptions";
import {PlatformLogMiddleware} from "../../platform/middlewares/PlatformLogMiddleware";
import {
callHook,
createContainer,
createInjector,
createPlatformApplication,
getConfiguration,
importProviders,
listenHttpServer,
listenHttpsServer,
loadInjector,
printRoutes,
setLoggerLevel
} from "../utils";
/**
* @platform
*/
export abstract class PlatformBuilder {
protected startedAt = new Date();
protected _rootModule: any;
protected _injector: InjectorService;
get injector(): InjectorService {
return this._injector;
}
get rootModule(): any {
return this._rootModule;
}
get app(): PlatformApplication {
return this.injector.get<PlatformApplication>(PlatformApplication)!;
}
get platform() {
return this.injector.get<Platform>(Platform)!;
}
/**
* Return the settings configured by the decorator @@Configuration@@.
*
* ```typescript
* @Configuration({
* rootDir: Path.resolve(__dirname),
* port: 8000,
* httpsPort: 8080,
* mount: {
* "/rest": "${rootDir}/controllers/**\/*.js"
* }
* })
* export class Server {
* $onInit(){
* console.log(this.settings); // {rootDir, port, httpsPort,...}
* }
* }
* ```
*
* @returns {ServerSettingsService}
*/
get settings() {
return this.injector.settings;
}
get logger() {
return this.injector.logger;
}
static build<T extends PlatformBuilder>(platformBuildClass: Type<T>): T {
return new platformBuildClass();
}
/**
* Add classes to the components list
* @param classes
*/
public addComponents(classes: any | any[]) {
this.settings.componentsScan = this.settings.componentsScan.concat(classes);
return this;
}
/**
* Add classes decorated by @@Controller@@ to components container.
*
* ### Example
*
* ```typescript
* @Controller('/ctrl')
* class MyController{
* }
*
* platform.addControllers('/rest', [MyController])
* ```
*
* ::: tip
* If the MyController class isn't decorated, the class will be ignored.
* :::
*
* @param {string} endpoint
* @param {any[]} controllers
*/
public addControllers(endpoint: string, controllers: any | string | (any | string)[]) {
this.settings.mount[endpoint] = (this.settings.mount[endpoint] || []).concat(controllers);
}
public async runLifecycle() {
setLoggerLevel(this.injector);
const routes = await importProviders(this.injector);
await this.loadInjector();
await this.createContext();
await this.loadRoutes(routes);
await this.logRoutes();
}
async loadInjector() {
const {injector, logger} = this;
await this.callHook("$beforeInit");
await this.callHook("$onInit");
logger.info("Build providers");
await loadInjector(injector, createContainer(constructorOf(this.rootModule)));
logger.debug("Settings and injector loaded");
await this.callHook("$afterInit");
}
async listen() {
const {logger, startedAt} = this;
await this.callHook("$beforeListen");
await this.listenServers();
await this.callHook("$afterListen");
await this.ready();
logger.info(`Started in ${new Date().getTime() - startedAt.getTime()} ms`);
}
public async ready() {
await this.callHook("$onReady");
await this.injector.emit("$onServerReady");
}
callHook(key: string, ...args: any[]) {
return callHook(this.injector, this.rootModule, key, ...args);
}
async loadStatics(): Promise<void> {
const {settings} = this;
if (settings.statics) {
Object.entries(settings.statics).forEach(([path, items]) => {
[].concat(items as any).forEach((options) => {
const opts =
typeof options === "string"
? {
root: options
}
: options;
this.platform.app.statics(path, opts);
});
});
}
}
protected async bootstrap(module: Type<any>, settings: Partial<TsED.Configuration> = {}) {
this.createInjector(module, settings);
this.createRootModule(module);
await this.runLifecycle();
return this;
}
protected async listenServers(): Promise<void> {
await Promise.all([listenHttpServer(this.injector), listenHttpsServer(this.injector)]);
}
protected logRoutes() {
const {logger, platform} = this;
if (!this.settings.logger.disableRoutesSummary) {
logger.info("Routes mounted :");
logger.info(printRoutes(platform.getRoutes()));
}
}
protected async createContext() {
const middleware = new PlatformContextMiddleware(this.injector);
return this.app.use(middleware.use.bind(middleware));
}
protected async loadRoutes(routes: IRoute[]) {
const {logger, platform} = this;
// istanbul ignore next
if (this.settings.logger.level !== "off") {
if (classOf(this.injector.get(LogIncomingRequestMiddleware)) !== LogIncomingRequestMiddleware) {
this.app.use(LogIncomingRequestMiddleware);
} else {
this.app.use(PlatformLogMiddleware);
}
}
if (this.settings.acceptMimes?.length) {
this.app.use(GlobalAcceptMimesMiddleware);
}
logger.info("Load routes");
await this.callHook("$beforeRoutesInit"); // deprecated
platform.addRoutes(routes);
await this.callHook("$onRoutesInit");
await this.loadStatics();
await this.callHook("$afterRoutesInit");
this.app.use(PlatformExceptionsMiddleware);
this.app.use(GlobalErrorHandlerMiddleware);
}
protected createInjector(module: Type<any>, settings: any) {
this._injector = createInjector(getConfiguration(module, settings));
createPlatformApplication(this.injector);
}
protected createRootModule(module: Type<any>) {
this._rootModule = this.injector.invoke(module, undefined, {
// imports: this.settings.imports
});
this.injector.delete(constructorOf(this._rootModule));
this.injector.delete(classOf(this._rootModule));
}
}