-
Notifications
You must be signed in to change notification settings - Fork 567
/
web.ts
302 lines (268 loc) · 8.96 KB
/
web.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import {
BaseFramework,
HTTP_SERVER_KEY,
httpError,
IMidwayBootstrapOptions,
MidwayProcessTypeEnum,
PathFileUtil,
RouterInfo,
WebControllerGenerator,
} from '@midwayjs/core';
import { Framework, Inject, MidwayFrameworkType } from '@midwayjs/decorator';
import { IMidwayWebConfigurationOptions } from '../interface';
import { EggRouter } from '@eggjs/router';
import { Application, Context, EggLogger } from 'egg';
import { loggers, MidwayContextLogger } from '@midwayjs/logger';
import { resolve } from 'path';
import { Server } from 'net';
import { debuglog } from 'util';
const debug = debuglog('midway:debug');
class EggControllerGenerator extends WebControllerGenerator<EggRouter> {
constructor(readonly app) {
super(app);
}
createRouter(routerOptions: any): EggRouter {
const router = new EggRouter(routerOptions, this.app);
router.prefix(routerOptions.prefix);
return router;
}
generateController(routeInfo: RouterInfo) {
return this.generateKoaController(routeInfo);
}
}
@Framework()
export class MidwayWebFramework extends BaseFramework<
Application,
Context,
IMidwayWebConfigurationOptions
> {
protected loggers: {
[name: string]: EggLogger;
};
generator: EggControllerGenerator;
private server: Server;
private agent;
private isClusterMode = false;
@Inject()
appDir;
public configure() {
process.env.EGG_TYPESCRIPT = 'true';
if (process.env['EGG_CLUSTER_MODE'] === 'true') {
this.isClusterMode = true;
}
return this.configService.getConfiguration('egg');
}
async initSingleProcessEgg() {
const opts = {
baseDir: this.appDir,
framework: resolve(__dirname, '../application'),
plugins: this.configurationOptions.plugins,
mode: 'single',
isTsMode: true,
applicationContext: this.applicationContext,
midwaySingleton: true,
};
debug('[egg]: init single process egg agent');
const Agent = require(opts.framework).Agent;
const Application = require(opts.framework).Application;
const agent = (this.agent = new Agent(Object.assign({}, opts)));
await agent.ready();
debug('[egg]: init single process egg application');
const application = (this.app = new Application(Object.assign({}, opts)));
application.agent = agent;
agent.application = application;
debug('[egg]: init single process egg end');
}
async applicationInitialize(options: Partial<IMidwayBootstrapOptions>) {
if (!this.isClusterMode) {
await this.initSingleProcessEgg();
} else {
// get app in cluster mode
this.app = options['application'];
}
// not found middleware
const notFound = async (ctx, next) => {
await next();
if (!ctx._matchedRoute && ctx.body === undefined) {
throw new httpError.NotFoundError(`${ctx.path} Not Found`);
}
};
// insert error handler
const midwayRootMiddleware = async (ctx, next) => {
// this.app.createAnonymousContext(ctx);
await (
await this.applyMiddleware(notFound)
)(ctx as any, next);
};
this.app.use(midwayRootMiddleware);
this.generator = new EggControllerGenerator(this.app);
this.overwriteApplication('app');
await new Promise<void>(resolve => {
this.app.once('application-ready', () => {
debug('[egg]: web framework: init egg end');
resolve();
});
(this.app.loader as any).loadOrigin();
// 这里拦截 app.use 方法,让他可以加到 midway 的 middlewareManager 中
(this.app as any).originUse = this.app.use;
this.app.use = this.app.useMiddleware as any;
this.app.ready();
});
}
overwriteApplication(processType) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
// 单进程下,先把egg的配置覆盖进来,有可能业务测没写 importConfigs
debug(`[egg]: overwrite egg config to configService in "${processType}"`);
this.configService.addObject(this.app.config);
Object.defineProperty(this.app, 'config', {
get() {
return self.getConfiguration();
},
});
debug(`[egg]: overwrite applicationContext config to "${processType}"`);
Object.defineProperty(this.app, 'applicationContext', {
get() {
return self.applicationContext;
},
});
debug(`[egg]: overwrite properties to "${processType}"`);
this.defineApplicationProperties(
{
generateController: (controllerMapping: string) => {
const [controllerId, methodName] = controllerMapping.split('.');
return this.generator.generateController({
id: controllerId,
method: methodName,
} as any);
},
generateMiddleware: async (middlewareId: any) => {
return this.generateMiddleware(middlewareId);
},
getProcessType: () => {
if (processType === 'app') {
return MidwayProcessTypeEnum.APPLICATION;
}
if (processType === 'agent') {
return MidwayProcessTypeEnum.AGENT;
}
},
},
['createAnonymousContext']
);
// if use midway logger will be use midway custom context logger
debug(`[egg]: overwrite BaseContextLoggerClass to "${processType}"`);
this.setContextLoggerClass();
}
async loadMidwayController() {
await this.generator.loadMidwayController(
this.configurationOptions.globalPrefix,
newRouter => {
const dispatchFn = newRouter.middleware();
dispatchFn._name = `midwayController(${
newRouter?.opts?.prefix || '/'
})`;
this.app.useMiddleware(dispatchFn);
}
);
}
getFrameworkType(): MidwayFrameworkType {
return MidwayFrameworkType.WEB;
}
async run(): Promise<void> {
// move egg router to last
this.app.getMiddleware().findAndInsertLast('eggRouterMiddleware');
// load controller
await this.loadMidwayController();
// restore use method
this.app.use = (this.app as any).originUse;
debug(`[egg]: current middleware = ${this.middlewareManager.getNames()}`);
if (!this.isClusterMode) {
// https config
if (this.configurationOptions.key && this.configurationOptions.cert) {
this.configurationOptions.key = PathFileUtil.getFileContentSync(
this.configurationOptions.key
);
this.configurationOptions.cert = PathFileUtil.getFileContentSync(
this.configurationOptions.cert
);
this.configurationOptions.ca = PathFileUtil.getFileContentSync(
this.configurationOptions.ca
);
if (this.configurationOptions.http2) {
this.server = require('http2').createSecureServer(
this.configurationOptions,
this.app.callback()
);
} else {
this.server = require('https').createServer(
this.configurationOptions,
this.app.callback()
);
}
} else {
if (this.configurationOptions.http2) {
this.server = require('http2').createServer(this.app.callback());
} else {
this.server = require('http').createServer(this.app.callback());
}
}
// emit egg-ready message in agent and application
this.app.messenger.broadcast('egg-ready', undefined);
// emit `server` event in app
this.app.emit('server', this.server);
// register httpServer to applicationContext
this.getApplicationContext().registerObject(HTTP_SERVER_KEY, this.server);
const eggConfig = this.configService.getConfiguration('egg');
if (!this.isClusterMode && eggConfig) {
const customPort = process.env.MIDWAY_HTTP_PORT ?? eggConfig.port;
if (customPort) {
new Promise<void>(resolve => {
const args: any[] = [customPort];
if (eggConfig.hostname) {
args.push(eggConfig.hostname);
}
args.push(() => {
resolve();
});
this.server.listen(...args);
process.env.MIDWAY_HTTP_PORT = String(customPort);
});
}
}
}
}
public getLogger(name?: string) {
if (name) {
return this.app.loggers[name] || loggers.getLogger(name);
}
return this.appLogger;
}
public setContextLoggerClass() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
class MidwayEggContextLogger extends MidwayContextLogger<Context> {
constructor(ctx, appLogger) {
super(ctx, appLogger, {
contextFormat: self.contextLoggerFormat,
});
}
}
this.app.ContextLogger = MidwayEggContextLogger as any;
}
public async generateMiddleware(middlewareId: any) {
const mwIns: any = await this.getApplicationContext().getAsync(
middlewareId
);
return mwIns.resolve();
}
async beforeStop() {
if (!this.isClusterMode) {
await new Promise(resolve => {
this.server.close(resolve);
});
await this.app.close();
await this.agent.close();
}
}
}