@midwayjs/express 3.0.0-beta.8 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # midway-web
1
+ # midway for express
2
2
 
3
- [![Package Quality](http://npm.packagequality.com/shield/midway-web.svg)](http://packagequality.com/#?package=midway-web)
3
+ [![Package Quality](http://npm.packagequality.com/shield/@midwayjs/express.svg)](http://packagequality.com/#?package=@midwayjs/express)
4
4
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/midwayjs/midway/pulls)
5
5
 
6
6
  this is a sub package for midway.
@@ -0,0 +1,22 @@
1
+ import { Options, OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';
2
+ import { CookieOptions } from 'express';
3
+ export declare const cookieParser: {
4
+ secret?: string | string[];
5
+ options?: CookieOptions;
6
+ };
7
+ export declare const bodyParser: {
8
+ enable?: boolean;
9
+ json?: OptionsJson & {
10
+ enable?: boolean;
11
+ };
12
+ raw?: Options & {
13
+ enable?: boolean;
14
+ };
15
+ text?: OptionsText & {
16
+ enable?: boolean;
17
+ };
18
+ urlencoded?: OptionsUrlencoded & {
19
+ enable?: boolean;
20
+ };
21
+ };
22
+ //# sourceMappingURL=config.default.d.ts.map
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bodyParser = exports.cookieParser = void 0;
4
+ exports.cookieParser = {};
5
+ exports.bodyParser = {
6
+ enable: true,
7
+ json: {
8
+ enable: true,
9
+ limit: '1mb',
10
+ strict: true,
11
+ },
12
+ raw: {
13
+ enable: false,
14
+ limit: '1mb',
15
+ },
16
+ text: {
17
+ enable: true,
18
+ limit: '1mb',
19
+ },
20
+ urlencoded: {
21
+ enable: true,
22
+ extended: false,
23
+ limit: '1mb',
24
+ parameterLimit: 1000,
25
+ },
26
+ };
27
+ //# sourceMappingURL=config.default.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.default.js","sourceRoot":"","sources":["../../src/config/config.default.ts"],"names":[],"mappings":";;;AAQa,QAAA,YAAY,GAGrB,EAAE,CAAC;AAEM,QAAA,UAAU,GAcnB;IACF,MAAM,EAAE,IAAI;IACZ,IAAI,EAAE;QACJ,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,IAAI;KACb;IACD,GAAG,EAAE;QACH,MAAM,EAAE,KAAK;QACb,KAAK,EAAE,KAAK;KACb;IACD,IAAI,EAAE;QACJ,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,KAAK;KACb;IACD,UAAU,EAAE;QACV,MAAM,EAAE,IAAI;QACZ,QAAQ,EAAE,KAAK;QACf,KAAK,EAAE,KAAK;QACZ,cAAc,EAAE,IAAI;KACrB;CACF,CAAC","sourcesContent":["import {\n Options,\n OptionsJson,\n OptionsText,\n OptionsUrlencoded,\n} from 'body-parser';\nimport { CookieOptions } from 'express';\n\nexport const cookieParser: {\n secret?: string | string[];\n options?: CookieOptions;\n} = {};\n\nexport const bodyParser: {\n enable?: boolean;\n json?: OptionsJson & {\n enable?: boolean;\n };\n raw?: Options & {\n enable?: boolean;\n };\n text?: OptionsText & {\n enable?: boolean;\n };\n urlencoded?: OptionsUrlencoded & {\n enable?: boolean;\n };\n} = {\n enable: true,\n json: {\n enable: true,\n limit: '1mb',\n strict: true,\n },\n raw: {\n enable: false,\n limit: '1mb',\n },\n text: {\n enable: true,\n limit: '1mb',\n },\n urlencoded: {\n enable: true,\n extended: false,\n limit: '1mb',\n parameterLimit: 1000,\n },\n};\n"]}
@@ -1,6 +1,9 @@
1
- import { MidwayDecoratorService } from '@midwayjs/core';
1
+ import { MidwayConfigService, MidwayDecoratorService } from '@midwayjs/core';
2
+ import { MidwayExpressFramework } from './framework';
2
3
  export declare class ExpressConfiguration {
3
4
  decoratorService: MidwayDecoratorService;
5
+ expressFramework: MidwayExpressFramework;
6
+ configService: MidwayConfigService;
4
7
  init(): void;
5
8
  onReady(): Promise<void>;
6
9
  }
@@ -12,18 +12,57 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ExpressConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const core_1 = require("@midwayjs/core");
15
+ const session = require("@midwayjs/express-session");
16
+ const framework_1 = require("./framework");
17
+ const bodyParser = require("body-parser");
18
+ const cookieParser = require("cookie-parser");
19
+ const DefaultConfig = require("./config/config.default");
15
20
  let ExpressConfiguration = class ExpressConfiguration {
16
21
  init() {
17
22
  this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
18
23
  return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData, options.originParamType)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
19
24
  });
20
25
  }
21
- async onReady() { }
26
+ async onReady() {
27
+ var _a, _b;
28
+ const keys = (_a = this.configService.getConfiguration('express.keys')) !== null && _a !== void 0 ? _a : this.configService.getConfiguration('keys');
29
+ const cookieParserConfig = this.configService.getConfiguration('cookieParser');
30
+ // add cookie parser middleware
31
+ this.expressFramework
32
+ .getMiddleware()
33
+ .insertFirst(cookieParser((_b = cookieParserConfig.secret) !== null && _b !== void 0 ? _b : keys, cookieParserConfig.options));
34
+ // add body parser
35
+ const bodyparserConfig = this.configService.getConfiguration('bodyParser');
36
+ if (bodyparserConfig.enable) {
37
+ // create application/json parser
38
+ if (bodyparserConfig.json.enable) {
39
+ this.expressFramework.useMiddleware(bodyParser.json(bodyparserConfig.json));
40
+ }
41
+ if (bodyparserConfig.raw.enable) {
42
+ this.expressFramework.useMiddleware(bodyParser.raw(bodyparserConfig.raw));
43
+ }
44
+ if (bodyparserConfig.text.enable) {
45
+ this.expressFramework.useMiddleware(bodyParser.text(bodyparserConfig.text));
46
+ }
47
+ // create application/x-www-form-urlencoded parser
48
+ if (bodyparserConfig.urlencoded.enable) {
49
+ this.expressFramework.useMiddleware(bodyParser.urlencoded(bodyparserConfig.urlencoded));
50
+ }
51
+ }
52
+ }
22
53
  };
23
54
  __decorate([
24
55
  (0, decorator_1.Inject)(),
25
56
  __metadata("design:type", core_1.MidwayDecoratorService)
26
57
  ], ExpressConfiguration.prototype, "decoratorService", void 0);
58
+ __decorate([
59
+ (0, decorator_1.Inject)(),
60
+ __metadata("design:type", framework_1.MidwayExpressFramework)
61
+ ], ExpressConfiguration.prototype, "expressFramework", void 0);
62
+ __decorate([
63
+ (0, decorator_1.Inject)(),
64
+ __metadata("design:type", core_1.MidwayConfigService)
65
+ ], ExpressConfiguration.prototype, "configService", void 0);
27
66
  __decorate([
28
67
  (0, decorator_1.Init)(),
29
68
  __metadata("design:type", Function),
@@ -33,6 +72,12 @@ __decorate([
33
72
  ExpressConfiguration = __decorate([
34
73
  (0, decorator_1.Configuration)({
35
74
  namespace: 'express',
75
+ imports: [session],
76
+ importConfigs: [
77
+ {
78
+ default: DefaultConfig,
79
+ },
80
+ ],
36
81
  })
37
82
  ], ExpressConfiguration);
38
83
  exports.ExpressConfiguration = ExpressConfiguration;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mDAK6B;AAC7B,yCAIwB;AACxB,qDAAqD;AACrD,2CAAqD;AACrD,0CAA0C;AAC1C,8CAA8C;AAC9C,yDAAyD;AAWzD,IAAa,oBAAoB,GAAjC,MAAa,oBAAoB;IAW/B,IAAI;QACF,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,CAC5C,gCAAoB,EACpB,OAAO,CAAC,EAAE;YACR,OAAO,IAAA,8BAAuB,EAC5B,OAAO,CAAC,QAAQ,CAAC,IAAI,EACrB,OAAO,CAAC,QAAQ,CAAC,YAAY,EAC7B,OAAO,CAAC,eAAe,CACxB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC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AAC,gBAAgB,CAAC,aAAa,CACjC,UAAU,CAAC,UAAU,CAAC,gBAAgB,CAAC,UAAU,CAAC,CACnD,CAAC;aACH;SACF;IACH,CAAC;CACF,CAAA;AAhEC;IADC,IAAA,kBAAM,GAAE;8BACS,6BAAsB;8DAAC;AAGzC;IADC,IAAA,kBAAM,GAAE;8BACS,kCAAsB;8DAAC;AAGzC;IADC,IAAA,kBAAM,GAAE;8BACM,0BAAmB;2DAAC;AAGnC;IADC,IAAA,gBAAI,GAAE;;;;gDAYN;AAtBU,oBAAoB;IAThC,IAAA,yBAAa,EAAC;QACb,SAAS,EAAE,SAAS;QACpB,OAAO,EAAE,CAAC,OAAO,CAAC;QAClB,aAAa,EAAE;YACb;gBACE,OAAO,EAAE,aAAa;aACvB;SACF;KACF,CAAC;GACW,oBAAoB,CAkEhC;AAlEY,oDAAoB","sourcesContent":["import {\n Configuration,\n Init,\n Inject,\n WEB_ROUTER_PARAM_KEY,\n} from '@midwayjs/decorator';\nimport {\n extractExpressLikeValue,\n MidwayConfigService,\n MidwayDecoratorService,\n} from '@midwayjs/core';\nimport * as session from '@midwayjs/express-session';\nimport { MidwayExpressFramework } from './framework';\nimport * as bodyParser from 'body-parser';\nimport * as cookieParser from 'cookie-parser';\nimport * as DefaultConfig from './config/config.default';\n\n@Configuration({\n namespace: 'express',\n imports: [session],\n importConfigs: [\n {\n default: DefaultConfig,\n },\n ],\n})\nexport class ExpressConfiguration {\n @Inject()\n decoratorService: MidwayDecoratorService;\n\n @Inject()\n expressFramework: MidwayExpressFramework;\n\n @Inject()\n configService: MidwayConfigService;\n\n @Init()\n init() {\n this.decoratorService.registerParameterHandler(\n WEB_ROUTER_PARAM_KEY,\n options => {\n return extractExpressLikeValue(\n options.metadata.type,\n options.metadata.propertyData,\n options.originParamType\n )(options.originArgs[0], options.originArgs[1], options.originArgs[2]);\n }\n );\n }\n\n async onReady() {\n const keys =\n this.configService.getConfiguration('express.keys') ??\n this.configService.getConfiguration('keys');\n const cookieParserConfig =\n this.configService.getConfiguration('cookieParser');\n // add cookie parser middleware\n this.expressFramework\n .getMiddleware()\n .insertFirst(\n cookieParser(\n cookieParserConfig.secret ?? keys,\n cookieParserConfig.options\n )\n );\n // add body parser\n const bodyparserConfig = this.configService.getConfiguration('bodyParser');\n if (bodyparserConfig.enable) {\n // create application/json parser\n if (bodyparserConfig.json.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.json(bodyparserConfig.json)\n );\n }\n if (bodyparserConfig.raw.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.raw(bodyparserConfig.raw)\n );\n }\n if (bodyparserConfig.text.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.text(bodyparserConfig.text)\n );\n }\n // create application/x-www-form-urlencoded parser\n if (bodyparserConfig.urlencoded.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.urlencoded(bodyparserConfig.urlencoded)\n );\n }\n }\n }\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  /// <reference types="node" />
2
2
  import { BaseFramework, IMidwayBootstrapOptions, MiddlewareRespond, MidwayFrameworkType, RouterInfo } from '@midwayjs/core';
3
- import { IMidwayExpressApplication, IMidwayExpressConfigurationOptions, IMidwayExpressContext } from './interface';
3
+ import { IMidwayExpressApplication, IMidwayExpressConfigurationOptions, Context } from './interface';
4
4
  import type { IRouter, IRouterHandler, Response, NextFunction } from 'express';
5
5
  import { Server } from 'net';
6
6
  import { MidwayExpressContextLogger } from './logger';
7
- export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpressApplication, IMidwayExpressContext, IMidwayExpressConfigurationOptions, Response, NextFunction> {
7
+ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpressApplication, Context, IMidwayExpressConfigurationOptions, Response, NextFunction> {
8
8
  app: IMidwayExpressApplication;
9
9
  private server;
10
10
  private expressMiddlewareService;
@@ -16,17 +16,20 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
16
16
  * wrap controller string to middleware function
17
17
  */
18
18
  protected generateController(routeInfo: RouterInfo): IRouterHandler<any>;
19
- loadMidwayController(): Promise<void>;
19
+ loadMidwayController(): Promise<Array<{
20
+ prefix: string;
21
+ middleware: any;
22
+ }>>;
20
23
  /**
21
24
  * @param routerOptions
22
25
  */
23
26
  protected createRouter(routerOptions: {
24
27
  sensitive: any;
25
28
  }): IRouter;
26
- private handlerWebMiddleware;
27
- getMiddleware<Response, NextFunction>(): Promise<MiddlewareRespond<IMidwayExpressContext, Response, NextFunction>>;
29
+ applyMiddleware<Response, NextFunction>(): Promise<MiddlewareRespond<Context, Response, NextFunction>>;
28
30
  beforeStop(): Promise<void>;
29
31
  getServer(): Server;
32
+ getPort(): string;
30
33
  getFrameworkName(): string;
31
34
  getDefaultContextLoggerClass(): typeof MidwayExpressContextLogger;
32
35
  }
package/dist/framework.js CHANGED
@@ -12,13 +12,19 @@ const decorator_1 = require("@midwayjs/decorator");
12
12
  const express = require("express");
13
13
  const logger_1 = require("./logger");
14
14
  const middlewareService_1 = require("./middlewareService");
15
+ const util_1 = require("util");
16
+ const util_2 = require("./util");
17
+ const debug = (0, util_1.debuglog)('midway:debug');
15
18
  let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
16
19
  configure() {
17
20
  return this.configService.getConfiguration('express');
18
21
  }
19
22
  async applicationInitialize(options) {
20
23
  this.expressMiddlewareService = await this.applicationContext.getAsync(middlewareService_1.MidwayExpressMiddlewareService, [this.applicationContext]);
24
+ debug('[express]: create express app');
21
25
  this.app = express();
26
+ debug('[express]: use root middleware');
27
+ // use root middleware
22
28
  this.app.use((req, res, next) => {
23
29
  const ctx = req;
24
30
  this.app.createAnonymousContext(ctx);
@@ -27,25 +33,71 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
27
33
  ctx.requestContext.registerObject('res', res);
28
34
  next();
29
35
  });
36
+ this.defineApplicationProperties();
37
+ // hack use method
38
+ this.app.originUse = this.app.use;
39
+ this.app.use = this.app.useMiddleware;
30
40
  }
31
41
  async run() {
32
42
  var _a;
43
+ debug(`[express]: use middlewares = "${this.getMiddleware().getNames()}"`);
44
+ // restore use method
45
+ this.app.use = this.app.originUse;
46
+ debug('[express]: use user router middleware');
47
+ // load controller,must apply router filter here
48
+ const routerMiddlewares = await this.loadMidwayController();
33
49
  // use global middleware
34
- const globalMiddleware = await this.getMiddleware();
50
+ const globalMiddleware = await this.applyMiddleware();
51
+ debug('[express]: use and apply all framework and global middleware');
35
52
  this.app.use(globalMiddleware);
36
- // load controller
37
- await this.loadMidwayController();
53
+ // load router after global middleware
54
+ for (const info of routerMiddlewares) {
55
+ this.app.use(info.prefix, info.middleware);
56
+ }
57
+ debug('[express]: use 404 not found middleware');
58
+ // eslint-disable-next-line
59
+ this.app.use(function notFound(req, res, next) {
60
+ next(new core_1.httpError.NotFoundError());
61
+ });
62
+ debug('[express]: use global error handler middleware');
38
63
  // use global error handler
39
- this.app.use(async (err, req, res, next) => {
40
- if (err) {
41
- const { result, error } = await this.filterManager.runErrorFilter(err, req, res, next);
64
+ this.app.use((err, req, res, next) => {
65
+ this.filterManager
66
+ .runErrorFilter(err, req, res, next)
67
+ .then(data => {
68
+ var _a, _b;
69
+ const { result, error } = data;
42
70
  if (error) {
71
+ const status = (_b = (_a = error.status) !== null && _a !== void 0 ? _a : res.statusCode) !== null && _b !== void 0 ? _b : 500;
72
+ // 5xx
73
+ if (status >= 500) {
74
+ try {
75
+ req.logger.error(err);
76
+ }
77
+ catch (ex) {
78
+ this.logger.error(err);
79
+ this.logger.error(ex);
80
+ }
81
+ return;
82
+ }
83
+ // 4xx
84
+ try {
85
+ req.logger.warn(err);
86
+ }
87
+ catch (ex) {
88
+ this.logger.warn(err);
89
+ this.logger.error(ex);
90
+ }
91
+ res.status(status);
43
92
  next(error);
44
93
  }
45
94
  else {
46
- res.send(result);
95
+ (0, util_2.sendData)(res, result);
47
96
  }
48
- }
97
+ })
98
+ .catch(err => {
99
+ next(err);
100
+ });
49
101
  });
50
102
  // https config
51
103
  if (this.configurationOptions.key && this.configurationOptions.cert) {
@@ -72,7 +124,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
72
124
  const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
73
125
  if (customPort) {
74
126
  new Promise(resolve => {
75
- const args = [this.configurationOptions.port];
127
+ const args = [customPort];
76
128
  if (this.configurationOptions.hostname) {
77
129
  args.push(this.configurationOptions.hostname);
78
130
  }
@@ -91,7 +143,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
91
143
  * wrap controller string to middleware function
92
144
  */
93
145
  generateController(routeInfo) {
94
- return async (req, res, next) => {
146
+ return (0, middlewareService_1.wrapAsyncHandler)(async (req, res, next) => {
95
147
  const controller = await req.requestContext.getAsync(routeInfo.id);
96
148
  const result = await controller[routeInfo.method].call(controller, req, res, next);
97
149
  if (res.headersSent) {
@@ -125,39 +177,49 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
125
177
  if (error) {
126
178
  throw error;
127
179
  }
128
- res.send(returnValue);
129
- };
180
+ (0, util_2.sendData)(res, returnValue);
181
+ });
130
182
  }
131
183
  async loadMidwayController() {
184
+ var _a, _b;
132
185
  const collector = new core_1.WebRouterCollector('', {
133
186
  globalPrefix: this.configurationOptions.globalPrefix,
134
187
  });
135
188
  const routerTable = await collector.getRouterTable();
136
189
  const routerList = await collector.getRoutePriorityList();
190
+ const routerMiddlewares = [];
137
191
  for (const routerInfo of routerList) {
138
192
  // bind controller first
139
193
  this.getApplicationContext().bindClass(routerInfo.routerModule);
140
194
  this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
141
195
  // new router
142
196
  const newRouter = this.createRouter(routerInfo.routerOptions);
197
+ routerInfo.middleware = (_a = routerInfo.middleware) !== null && _a !== void 0 ? _a : [];
143
198
  // add router middleware
144
- await this.handlerWebMiddleware(routerInfo.middleware, middlewareImpl => {
145
- newRouter.use(middlewareImpl);
146
- });
199
+ if (routerInfo.middleware.length) {
200
+ const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
201
+ newRouter.use(routerMiddlewareFn);
202
+ }
147
203
  // add route
148
204
  const routes = routerTable.get(routerInfo.prefix);
149
205
  for (const routeInfo of routes) {
150
206
  const routeMiddlewareList = [];
151
- // router middleware
152
- await this.handlerWebMiddleware(routeInfo.middleware, middlewareImpl => {
153
- routeMiddlewareList.push(middlewareImpl);
154
- });
207
+ // routeInfo middleware
208
+ routeInfo.middleware = (_b = routeInfo.middleware) !== null && _b !== void 0 ? _b : [];
209
+ if (routeInfo.middleware.length) {
210
+ const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
211
+ routeMiddlewareList.push(routeMiddlewareFn);
212
+ }
155
213
  this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
156
214
  // apply controller from request context
157
215
  newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
158
216
  }
159
- this.app.use(routerInfo.prefix, newRouter);
217
+ routerMiddlewares.push({
218
+ prefix: routerInfo.prefix,
219
+ middleware: newRouter,
220
+ });
160
221
  }
222
+ return routerMiddlewares;
161
223
  }
162
224
  /**
163
225
  * @param routerOptions
@@ -165,13 +227,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
165
227
  createRouter(routerOptions) {
166
228
  return express.Router({ caseSensitive: routerOptions.sensitive });
167
229
  }
168
- async handlerWebMiddleware(middlewares, handlerCallback) {
169
- const fn = await this.expressMiddlewareService.compose(middlewares);
170
- handlerCallback(fn);
171
- }
172
- async getMiddleware() {
230
+ async applyMiddleware() {
173
231
  if (!this.composeMiddleware) {
174
- this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager);
232
+ this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager, this.app);
175
233
  await this.filterManager.init(this.applicationContext);
176
234
  }
177
235
  return this.composeMiddleware;
@@ -182,6 +240,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
182
240
  getServer() {
183
241
  return this.server;
184
242
  }
243
+ getPort() {
244
+ return process.env.MIDWAY_HTTP_PORT;
245
+ }
185
246
  getFrameworkName() {
186
247
  return 'midway:express';
187
248
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"framework.js","sourceRoot":"","sources":["../src/framework.ts"],"names":[],"mappings":";;;;;;;;;AAAA,yCAUwB;AAExB,mDAM6B;AAO7B,mCAAmC;AAEnC,qCAAsD;AACtD,2DAG6B;AAC7B,+BAAgC;AAChC,iCAAkC;AAClC,MAAM,KAAK,GAAG,IAAA,eAAQ,EAAC,cAAc,CAAC,CAAC;AAGvC,IAAa,sBAAsB,GAAnC,MAAa,sBAAuB,SAAQ,oBAM3C;IAKC,SAAS;QACP,OAAO,IAAI,CAAC,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;IAED,KAAK,CAAC,qBAAqB,CAAC,OAAyC;QACnE,IAAI,CAAC,wBAAwB,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CACpE,kDAA8B,EAC9B,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAC1B,CAAC;QACF,KAAK,CAAC,+BAA+B,CAAC,CAAC;QACvC,IAAI,CAAC,GAAG,GAAG,OAAO,EAA0C,CAAC;QAC7D,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACxC,sBAAsB;QACtB,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YAC9B,MAAM,GAAG,GAAG,GAAc,CAAC;YAC3B,IAAI,CAAC,GAAG,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC;YACpC,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC,cAAc,CAAC;YACjD,GAAG,CAAC,cAAc,CAAC,cAAc,C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gBAAgB,CAAC;IACtC,CAAC;IAEM,gBAAgB;QACrB,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IAEM,4BAA4B;QACjC,OAAO,mCAA0B,CAAC;IACpC,CAAC;CACF,CAAA;AArUY,sBAAsB;IADlC,IAAA,qBAAS,GAAE;GACC,sBAAsB,CAqUlC;AArUY,wDAAsB","sourcesContent":["import {\n BaseFramework,\n HTTP_SERVER_KEY,\n IMidwayBootstrapOptions,\n MiddlewareRespond,\n MidwayFrameworkType,\n PathFileUtil,\n WebRouterCollector,\n RouterInfo,\n httpError,\n} from '@midwayjs/core';\n\nimport {\n Framework,\n WEB_RESPONSE_CONTENT_TYPE,\n WEB_RESPONSE_HEADER,\n WEB_RESPONSE_HTTP_CODE,\n WEB_RESPONSE_REDIRECT,\n} from '@midwayjs/decorator';\nimport {\n IMidwayExpressApplication,\n IMidwayExpressConfigurationOptions,\n Context,\n} from './interface';\nimport type { IRouter, IRouterHandler, Response, NextFunction } from 'express';\nimport * as express from 'express';\nimport { Server } from 'net';\nimport { MidwayExpressContextLogger } from './logger';\nimport {\n wrapAsyncHandler,\n MidwayExpressMiddlewareService,\n} from './middlewareService';\nimport { debuglog } from 'util';\nimport { sendData } from './util';\nconst debug = debuglog('midway:debug');\n\n@Framework()\nexport class MidwayExpressFramework extends BaseFramework<\n IMidwayExpressApplication,\n Context,\n IMidwayExpressConfigurationOptions,\n Response,\n NextFunction\n> {\n public app: IMidwayExpressApplication;\n private server: Server;\n private expressMiddlewareService: MidwayExpressMiddlewareService;\n\n configure(): IMidwayExpressConfigurationOptions {\n return this.configService.getConfiguration('express');\n }\n\n async applicationInitialize(options: Partial<IMidwayBootstrapOptions>) {\n this.expressMiddlewareService = await this.applicationContext.getAsync(\n MidwayExpressMiddlewareService,\n [this.applicationContext]\n );\n debug('[express]: create express app');\n this.app = express() as unknown as IMidwayExpressApplication;\n debug('[express]: use root middleware');\n // use root middleware\n this.app.use((req, res, next) => {\n const ctx = req as Context;\n this.app.createAnonymousContext(ctx);\n (req as any).requestContext = ctx.requestContext;\n ctx.requestContext.registerObject('req', req);\n ctx.requestContext.registerObject('res', res);\n next();\n });\n\n this.defineApplicationProperties();\n\n // hack use method\n (this.app as any).originUse = this.app.use;\n this.app.use = this.app.useMiddleware as any;\n }\n\n public async run(): Promise<void> {\n debug(`[express]: use middlewares = \"${this.getMiddleware().getNames()}\"`);\n // restore use method\n this.app.use = (this.app as any).originUse;\n\n debug('[express]: use user router middleware');\n // load controller,must apply router filter here\n const routerMiddlewares = await this.loadMidwayController();\n\n // use global middleware\n const globalMiddleware = await this.applyMiddleware();\n debug('[express]: use and apply all framework and global middleware');\n this.app.use(globalMiddleware as any);\n\n // load router after global middleware\n for (const info of routerMiddlewares) {\n this.app.use(info.prefix, info.middleware);\n }\n\n debug('[express]: use 404 not found middleware');\n // eslint-disable-next-line\n this.app.use(function notFound(req, res, next) {\n next(new httpError.NotFoundError());\n });\n\n debug('[express]: use global error handler middleware');\n // use global error handler\n this.app.use((err, req, res, next) => {\n this.filterManager\n .runErrorFilter(err, req, res, next)\n .then(data => {\n const { result, error } = data;\n if (error) {\n const status = error.status ?? res.statusCode ?? 500;\n // 5xx\n if (status >= 500) {\n try {\n req.logger.error(err);\n } catch (ex) {\n this.logger.error(err);\n this.logger.error(ex);\n }\n return;\n }\n\n // 4xx\n try {\n req.logger.warn(err);\n } catch (ex) {\n this.logger.warn(err);\n this.logger.error(ex);\n }\n\n res.status(status);\n next(error);\n } else {\n sendData(res, result);\n }\n })\n .catch(err => {\n next(err);\n });\n });\n\n // https config\n if (this.configurationOptions.key && this.configurationOptions.cert) {\n this.configurationOptions.key = PathFileUtil.getFileContentSync(\n this.configurationOptions.key\n );\n this.configurationOptions.cert = PathFileUtil.getFileContentSync(\n this.configurationOptions.cert\n );\n this.configurationOptions.ca = PathFileUtil.getFileContentSync(\n this.configurationOptions.ca\n );\n\n if (this.configurationOptions.http2) {\n this.server = require('http2').createSecureServer(\n this.configurationOptions,\n this.app\n );\n } else {\n this.server = require('https').createServer(\n this.configurationOptions,\n this.app\n );\n }\n } else {\n if (this.configurationOptions.http2) {\n this.server = require('http2').createServer(this.app);\n } else {\n this.server = require('http').createServer(this.app);\n }\n }\n // register httpServer to applicationContext\n this.applicationContext.registerObject(HTTP_SERVER_KEY, this.server);\n\n const customPort =\n process.env.MIDWAY_HTTP_PORT ?? this.configurationOptions.port;\n if (customPort) {\n new Promise<void>(resolve => {\n const args: any[] = [customPort];\n if (this.configurationOptions.hostname) {\n args.push(this.configurationOptions.hostname);\n }\n args.push(() => {\n resolve();\n });\n\n this.server.listen(...args);\n process.env.MIDWAY_HTTP_PORT = String(customPort);\n });\n }\n }\n\n public getFrameworkType(): MidwayFrameworkType {\n return MidwayFrameworkType.WEB_EXPRESS;\n }\n\n /**\n * wrap controller string to middleware function\n */\n protected generateController(routeInfo: RouterInfo): IRouterHandler<any> {\n return wrapAsyncHandler(async (req, res, next) => {\n const controller = await req.requestContext.getAsync(routeInfo.id);\n\n const result = await controller[routeInfo.method].call(\n controller,\n req,\n res,\n next\n );\n\n if (res.headersSent) {\n // return when response send\n return;\n }\n\n if (res.statusCode === 200 && (result === null || result === undefined)) {\n res.status(204);\n }\n // implement response decorator\n if (\n Array.isArray(routeInfo.responseMetadata) &&\n routeInfo.responseMetadata.length\n ) {\n for (const routerRes of routeInfo.responseMetadata) {\n switch (routerRes.type) {\n case WEB_RESPONSE_HTTP_CODE:\n res.status(routerRes.code);\n break;\n case WEB_RESPONSE_HEADER:\n res.set(routerRes.setHeaders);\n break;\n case WEB_RESPONSE_CONTENT_TYPE:\n res.type(routerRes.contentType);\n break;\n case WEB_RESPONSE_REDIRECT:\n res.redirect(routerRes.code, routerRes.url);\n return;\n }\n }\n }\n\n const { result: returnValue, error } =\n await this.filterManager.runResultFilter(result, req, res, next);\n\n if (error) {\n throw error;\n }\n\n sendData(res, returnValue);\n });\n }\n\n public async loadMidwayController(): Promise<\n Array<{\n prefix: string;\n middleware: any;\n }>\n > {\n const collector = new WebRouterCollector('', {\n globalPrefix: this.configurationOptions.globalPrefix,\n });\n const routerTable = await collector.getRouterTable();\n const routerList = await collector.getRoutePriorityList();\n const routerMiddlewares = [];\n\n for (const routerInfo of routerList) {\n // bind controller first\n this.getApplicationContext().bindClass(routerInfo.routerModule);\n\n this.logger.debug(\n `Load Controller \"${routerInfo.controllerId}\", prefix=${routerInfo.prefix}`\n );\n\n // new router\n const newRouter = this.createRouter(routerInfo.routerOptions);\n\n routerInfo.middleware = routerInfo.middleware ?? [];\n // add router middleware\n if (routerInfo.middleware.length) {\n const routerMiddlewareFn = await this.expressMiddlewareService.compose(\n routerInfo.middleware,\n this.app\n );\n newRouter.use(routerMiddlewareFn);\n }\n\n // add route\n const routes = routerTable.get(routerInfo.prefix);\n for (const routeInfo of routes) {\n const routeMiddlewareList = [];\n // routeInfo middleware\n routeInfo.middleware = routeInfo.middleware ?? [];\n if (routeInfo.middleware.length) {\n const routeMiddlewareFn = await this.expressMiddlewareService.compose(\n routeInfo.middleware,\n this.app\n );\n routeMiddlewareList.push(routeMiddlewareFn);\n }\n\n this.logger.debug(\n `Load Router \"${routeInfo.requestMethod.toUpperCase()} ${\n routeInfo.url\n }\"`\n );\n\n // apply controller from request context\n newRouter[routeInfo.requestMethod].call(\n newRouter,\n routeInfo.url,\n ...routeMiddlewareList,\n this.generateController(routeInfo)\n );\n }\n\n routerMiddlewares.push({\n prefix: routerInfo.prefix,\n middleware: newRouter,\n });\n }\n return routerMiddlewares;\n }\n\n /**\n * @param routerOptions\n */\n protected createRouter(routerOptions: { sensitive }): IRouter {\n return express.Router({ caseSensitive: routerOptions.sensitive });\n }\n\n public async applyMiddleware<Response, NextFunction>(): Promise<\n MiddlewareRespond<Context, Response, NextFunction>\n > {\n if (!this.composeMiddleware) {\n this.composeMiddleware = await this.expressMiddlewareService.compose(\n this.middlewareManager,\n this.app\n );\n await this.filterManager.init(this.applicationContext);\n }\n return this.composeMiddleware;\n }\n\n public async beforeStop() {\n this.server.close();\n }\n\n public getServer() {\n return this.server;\n }\n\n public getPort() {\n return process.env.MIDWAY_HTTP_PORT;\n }\n\n public getFrameworkName() {\n return 'midway:express';\n }\n\n public getDefaultContextLoggerClass() {\n return MidwayExpressContextLogger;\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,yCAAkE;AAAzD,sGAAA,sBAAsB,OAAa;AAC5C,iDAAwE;AAA/D,8GAAA,oBAAoB,OAAiB;AAC9C,sDAAoC;AACpC,2CAAyB","sourcesContent":["export * from './interface';\nexport { MidwayExpressFramework as Framework } from './framework';\nexport { ExpressConfiguration as Configuration } from './configuration';\nexport * from './middlewareService';\nexport * from './logger';\n"]}
@@ -1,24 +1,37 @@
1
1
  /// <reference types="node" />
2
2
  import { CommonMiddlewareUnion, ContextMiddlewareManager, IConfigurationOptions, IMiddleware, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
3
- import { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request, Response } from 'express';
4
- export declare type IMidwayExpressContext = IMidwayContext<Request>;
3
+ import { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request as ExpressRequest, Response as ExpressResponse } from 'express';
4
+ import { Options, OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';
5
+ declare type Request = IMidwayContext<ExpressRequest>;
6
+ export declare type Response = ExpressResponse;
7
+ export declare type NextFunction = ExpressNextFunction;
8
+ export interface Context extends Request {
9
+ }
10
+ /**
11
+ * @deprecated use Context
12
+ */
13
+ export declare type IMidwayExpressRequest = Context;
5
14
  /**
6
- * @deprecated use IMidwayExpressContext
15
+ * @deprecated use Context
7
16
  */
8
- export declare type IMidwayExpressRequest = IMidwayExpressContext;
9
- export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, ExpressNextFunction>;
10
- export interface IMidwayExpressApplication extends IMidwayApplication<IMidwayExpressContext, ExpressApplication> {
17
+ export declare type IMidwayExpressContext = Context;
18
+ export declare type IMidwayExpressMiddleware = IMiddleware<Context, ExpressResponse, ExpressNextFunction>;
19
+ export interface IMidwayExpressApplication extends IMidwayApplication<Context, ExpressApplication> {
11
20
  /**
12
21
  * add global middleware to app
13
22
  * @param Middleware
14
23
  */
15
- useMiddleware<Response, NextFunction>(Middleware: CommonMiddlewareUnion<IMidwayExpressContext, Response, NextFunction>): void;
24
+ useMiddleware<Response, NextFunction>(Middleware: CommonMiddlewareUnion<Context, Response, NextFunction>): void;
16
25
  /**
17
26
  * get global middleware
18
27
  */
19
- getMiddleware<Response, NextFunction>(): ContextMiddlewareManager<IMidwayExpressContext, Response, NextFunction>;
28
+ getMiddleware<Response, NextFunction>(): ContextMiddlewareManager<Context, Response, NextFunction>;
20
29
  }
21
30
  export interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {
31
+ /**
32
+ * session or cookie secret key
33
+ */
34
+ keys?: string | string[];
22
35
  /**
23
36
  * application http port
24
37
  */
@@ -49,12 +62,25 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
49
62
  globalPrefix?: string;
50
63
  }
51
64
  export declare type Application = IMidwayExpressApplication;
52
- export declare type NextFunction = ExpressNextFunction;
53
- export interface Context extends IMidwayExpressContext {
54
- }
55
65
  declare module '@midwayjs/core/dist/interface' {
56
66
  interface MidwayConfig {
57
67
  express?: IMidwayExpressConfigurationOptions;
68
+ bodyParser?: {
69
+ enable?: boolean;
70
+ json?: OptionsJson & {
71
+ enable?: boolean;
72
+ };
73
+ raw?: Options & {
74
+ enable?: boolean;
75
+ };
76
+ text?: OptionsText & {
77
+ enable?: boolean;
78
+ };
79
+ urlencoded?: OptionsUrlencoded & {
80
+ enable?: boolean;
81
+ };
82
+ };
58
83
  }
59
84
  }
85
+ export {};
60
86
  //# sourceMappingURL=interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interface.js","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":"","sourcesContent":["import {\n CommonMiddlewareUnion,\n ContextMiddlewareManager,\n IConfigurationOptions,\n IMiddleware,\n IMidwayApplication,\n IMidwayContext\n} from '@midwayjs/core';\nimport { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request as ExpressRequest, Response as ExpressResponse } from 'express';\nimport { Options, OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';\n\ntype Request = IMidwayContext<ExpressRequest>;\nexport type Response = ExpressResponse;\nexport type NextFunction = ExpressNextFunction;\nexport interface Context extends Request {}\n\n/**\n * @deprecated use Context\n */\nexport type IMidwayExpressRequest = Context;\n/**\n * @deprecated use Context\n */\nexport type IMidwayExpressContext = Context;\nexport type IMidwayExpressMiddleware = IMiddleware<Context, ExpressResponse, ExpressNextFunction>;\nexport interface IMidwayExpressApplication extends IMidwayApplication<Context, ExpressApplication> {\n /**\n * add global middleware to app\n * @param Middleware\n */\n useMiddleware<Response, NextFunction>(Middleware: CommonMiddlewareUnion<Context, Response, NextFunction>): void;\n\n /**\n * get global middleware\n */\n getMiddleware<Response, NextFunction>(): ContextMiddlewareManager<Context, Response, NextFunction>;\n}\n\nexport interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {\n /**\n * session or cookie secret key\n */\n keys?: string | string[];\n /**\n * application http port\n */\n port?: number;\n /**\n * application hostname, 127.0.0.1 as default\n */\n hostname?: string;\n /**\n * https key\n */\n key?: string | Buffer | Array<Buffer | Object>;\n /**\n * https cert\n */\n cert?: string | Buffer | Array<string | Buffer>;\n /**\n * https ca\n */\n ca?: string | Buffer | Array<string | Buffer>;\n /**\n * http2 support\n */\n http2?: boolean;\n /**\n * http global prefix\n */\n globalPrefix?: string;\n}\n\nexport type Application = IMidwayExpressApplication;\n\ndeclare module '@midwayjs/core/dist/interface' {\n interface MidwayConfig {\n express?: IMidwayExpressConfigurationOptions;\n bodyParser?: {\n enable?: boolean;\n json?: OptionsJson & {\n enable?: boolean;\n };\n raw?: Options & {\n enable?: boolean;\n };\n text?: OptionsText & {\n enable?: boolean;\n };\n urlencoded?: OptionsUrlencoded & {\n enable?: boolean;\n };\n }\n }\n}\n"]}
package/dist/logger.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MidwayContextLogger } from '@midwayjs/logger';
2
- import { IMidwayExpressContext } from './interface';
3
- export declare class MidwayExpressContextLogger extends MidwayContextLogger<IMidwayExpressContext> {
2
+ import { Context } from './interface';
3
+ export declare class MidwayExpressContextLogger extends MidwayContextLogger<Context> {
4
4
  formatContextLabel(): string;
5
5
  }
6
6
  //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;AAAA,6CAAuD;AAGvD,MAAa,0BAA2B,SAAQ,4BAA4B;IAC1E,kBAAkB;;QAChB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACrB,wDAAwD;QACxD,MAAM,MAAM,GAAG,CAAA,MAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAG,SAAS,CAAC,0CAAG,QAAQ,CAAC,KAAI,GAAG,CAAC;QACnD,MAAM,OAAO,GAAG,GAAG,CAAC;QACpB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC;QAC5C,OAAO,CACL,MAAM;YACN,GAAG;YACH,GAAG,CAAC,EAAE;YACN,GAAG;YACH,OAAO;YACP,GAAG;YACH,GAAG;YACH,KAAK;YACL,GAAG,CAAC,MAAM;YACV,GAAG;YACH,GAAG,CAAC,GAAG,CACR,CAAC;IACJ,CAAC;CACF;AArBD,gEAqBC","sourcesContent":["import { MidwayContextLogger } from '@midwayjs/logger';\nimport { Context } from './interface';\n\nexport class MidwayExpressContextLogger extends MidwayContextLogger<Context> {\n formatContextLabel() {\n const req = this.ctx;\n // format: '[$userId/$ip/$traceId/$use_ms $method $url]'\n const userId = req?.['session']?.['userId'] || '-';\n const traceId = '-';\n const use = Date.now() - this.ctx.startTime;\n return (\n userId +\n '/' +\n req.ip +\n '/' +\n traceId +\n '/' +\n use +\n 'ms ' +\n req.method +\n ' ' +\n req.url\n );\n }\n}\n"]}
@@ -1,11 +1,12 @@
1
1
  import { IMidwayContainer, CommonMiddleware, FunctionMiddleware } from '@midwayjs/core';
2
- import { IMidwayExpressContext } from './interface';
2
+ import { Context, Application } from './interface';
3
3
  import { NextFunction, Response } from 'express';
4
+ export declare function wrapAsyncHandler(fn: any): any;
4
5
  export declare class MidwayExpressMiddlewareService {
5
6
  readonly applicationContext: IMidwayContainer;
6
7
  constructor(applicationContext: IMidwayContainer);
7
- compose(middleware: Array<CommonMiddleware<IMidwayExpressContext, Response, NextFunction> | string>, name?: string): Promise<{
8
- (req: IMidwayExpressContext, res: Response, next: NextFunction): void;
8
+ compose(middleware: Array<CommonMiddleware<Context, Response, NextFunction> | string>, app: Application, name?: string): Promise<{
9
+ (req: Context, res: Response, nextFunction: NextFunction): any;
9
10
  _name: string;
10
11
  }>;
11
12
  }