@midwayjs/express 3.0.0-beta.1 → 3.0.0-beta.13

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/CHANGELOG.md CHANGED
@@ -3,6 +3,128 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [3.0.0-beta.13](https://github.com/midwayjs/midway/compare/v3.0.0-beta.12...v3.0.0-beta.13) (2021-12-30)
7
+
8
+
9
+ ### Features
10
+
11
+ * 404 error ([#1465](https://github.com/midwayjs/midway/issues/1465)) ([e7e8a9d](https://github.com/midwayjs/midway/commit/e7e8a9dedfa7198ac05b161b41024c2871f93965))
12
+
13
+
14
+
15
+
16
+
17
+ # [3.0.0-beta.12](https://github.com/midwayjs/midway/compare/v3.0.0-beta.11...v3.0.0-beta.12) (2021-12-28)
18
+
19
+
20
+ ### Features
21
+
22
+ * custom error code & add @Files/@Fields ([#1438](https://github.com/midwayjs/midway/issues/1438)) ([b0032af](https://github.com/midwayjs/midway/commit/b0032afd2fa9ea0416fe69f4bd0c1a58bea5314e))
23
+ * support throw err status ([#1440](https://github.com/midwayjs/midway/issues/1440)) ([7b98110](https://github.com/midwayjs/midway/commit/7b98110d65c5287a8fcb3eb5356dea2d7a32cee9))
24
+
25
+
26
+
27
+
28
+
29
+ # [3.0.0-beta.11](https://github.com/midwayjs/midway/compare/v3.0.0-beta.10...v3.0.0-beta.11) (2021-12-21)
30
+
31
+ **Note:** Version bump only for package @midwayjs/express
32
+
33
+
34
+
35
+
36
+
37
+ # [3.0.0-beta.10](https://github.com/midwayjs/midway/compare/v3.0.0-beta.9...v3.0.0-beta.10) (2021-12-20)
38
+
39
+
40
+ ### Features
41
+
42
+ * default add session & bodyparser support for koa/express/faas ([#1420](https://github.com/midwayjs/midway/issues/1420)) ([cdaff31](https://github.com/midwayjs/midway/commit/cdaff317c3e862a95494a167995a28280af639bf))
43
+ * implement i18n for validate ([#1426](https://github.com/midwayjs/midway/issues/1426)) ([4c7ed2f](https://github.com/midwayjs/midway/commit/4c7ed2ff2e7ccf10f88f62abad230f92f5e76b97))
44
+
45
+
46
+
47
+
48
+
49
+ # [3.0.0-beta.9](https://github.com/midwayjs/midway/compare/v3.0.0-beta.8...v3.0.0-beta.9) (2021-12-09)
50
+
51
+ **Note:** Version bump only for package @midwayjs/express
52
+
53
+
54
+
55
+
56
+
57
+ # [3.0.0-beta.8](https://github.com/midwayjs/midway/compare/v3.0.0-beta.7...v3.0.0-beta.8) (2021-12-08)
58
+
59
+
60
+ ### Bug Fixes
61
+
62
+ * express routing middleware takes effect at the controller level ([#1364](https://github.com/midwayjs/midway/issues/1364)) ([b9272e0](https://github.com/midwayjs/midway/commit/b9272e0971003443304b0c53815be31a0061b4bd))
63
+ * typeorm EntityView missing connectionName ([#1403](https://github.com/midwayjs/midway/issues/1403)) ([30b2b37](https://github.com/midwayjs/midway/commit/30b2b3711db485cb85d825d56aeabf53b1374cae))
64
+
65
+
66
+
67
+
68
+
69
+ # [3.0.0-beta.7](https://github.com/midwayjs/midway/compare/v3.0.0-beta.6...v3.0.0-beta.7) (2021-12-03)
70
+
71
+ **Note:** Version bump only for package @midwayjs/express
72
+
73
+
74
+
75
+
76
+
77
+ # [3.0.0-beta.6](https://github.com/midwayjs/midway/compare/v3.0.0-beta.5...v3.0.0-beta.6) (2021-11-26)
78
+
79
+
80
+ ### Bug Fixes
81
+
82
+ * class transformer method missing ([#1387](https://github.com/midwayjs/midway/issues/1387)) ([074e839](https://github.com/midwayjs/midway/commit/074e8393598dc95e2742f735df75a2191c5fe25d))
83
+
84
+
85
+
86
+
87
+
88
+ # [3.0.0-beta.5](https://github.com/midwayjs/midway/compare/v3.0.0-beta.4...v3.0.0-beta.5) (2021-11-25)
89
+
90
+ **Note:** Version bump only for package @midwayjs/express
91
+
92
+
93
+
94
+
95
+
96
+ # [3.0.0-beta.4](https://github.com/midwayjs/midway/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-11-24)
97
+
98
+
99
+ ### Features
100
+
101
+ * add i18n ([#1375](https://github.com/midwayjs/midway/issues/1375)) ([bffefe0](https://github.com/midwayjs/midway/commit/bffefe07afe45777d49b5a76b9ab17fc2b9d9a55))
102
+ * auto transform args to type ([#1372](https://github.com/midwayjs/midway/issues/1372)) ([bb3f7d2](https://github.com/midwayjs/midway/commit/bb3f7d2028a034e1926d9df554849332354c3762))
103
+ * support global prefix url ([#1371](https://github.com/midwayjs/midway/issues/1371)) ([cc5fe44](https://github.com/midwayjs/midway/commit/cc5fe44e1d221590562dc71e1f33ae96093e0da7))
104
+
105
+
106
+
107
+
108
+
109
+ # [3.0.0-beta.3](https://github.com/midwayjs/midway/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-11-18)
110
+
111
+
112
+ ### Features
113
+
114
+ * add component and framework config definition ([#1367](https://github.com/midwayjs/midway/issues/1367)) ([b2fe615](https://github.com/midwayjs/midway/commit/b2fe6157f99659471ff1333eca0b86bb889f61a3))
115
+
116
+
117
+
118
+
119
+
120
+ # [3.0.0-beta.2](https://github.com/midwayjs/midway/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-11-16)
121
+
122
+ **Note:** Version bump only for package @midwayjs/express
123
+
124
+
125
+
126
+
127
+
6
128
  # [3.0.0-beta.1](https://github.com/midwayjs/midway/compare/v2.12.4...v3.0.0-beta.1) (2021-11-14)
7
129
 
8
130
 
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  this is a sub package for midway.
7
7
 
8
- Document: [https://midwayjs.org/midway](https://midwayjs.org/midway)
8
+ Document: [https://midwayjs.org](https://midwayjs.org)
9
9
 
10
10
  ## License
11
11
 
@@ -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
@@ -1,10 +1,10 @@
1
+ import { MidwayConfigService, MidwayDecoratorService } from '@midwayjs/core';
1
2
  import { MidwayExpressFramework } from './framework';
2
- import { MidwayDecoratorService } from '@midwayjs/core';
3
3
  export declare class ExpressConfiguration {
4
- framework: MidwayExpressFramework;
5
4
  decoratorService: MidwayDecoratorService;
5
+ expressFramework: MidwayExpressFramework;
6
+ configService: MidwayConfigService;
6
7
  init(): void;
7
8
  onReady(): Promise<void>;
8
- onServerReady(): Promise<void>;
9
9
  }
10
10
  //# sourceMappingURL=configuration.d.ts.map
@@ -11,27 +11,58 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ExpressConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
- const framework_1 = require("./framework");
15
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");
16
20
  let ExpressConfiguration = class ExpressConfiguration {
17
21
  init() {
18
22
  this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
19
- return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
23
+ return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData, options.originParamType)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
20
24
  });
21
25
  }
22
- async onReady() { }
23
- async onServerReady() {
24
- await this.framework.run();
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
+ }
25
52
  }
26
53
  };
54
+ __decorate([
55
+ (0, decorator_1.Inject)(),
56
+ __metadata("design:type", core_1.MidwayDecoratorService)
57
+ ], ExpressConfiguration.prototype, "decoratorService", void 0);
27
58
  __decorate([
28
59
  (0, decorator_1.Inject)(),
29
60
  __metadata("design:type", framework_1.MidwayExpressFramework)
30
- ], ExpressConfiguration.prototype, "framework", void 0);
61
+ ], ExpressConfiguration.prototype, "expressFramework", void 0);
31
62
  __decorate([
32
63
  (0, decorator_1.Inject)(),
33
- __metadata("design:type", core_1.MidwayDecoratorService)
34
- ], ExpressConfiguration.prototype, "decoratorService", void 0);
64
+ __metadata("design:type", core_1.MidwayConfigService)
65
+ ], ExpressConfiguration.prototype, "configService", void 0);
35
66
  __decorate([
36
67
  (0, decorator_1.Init)(),
37
68
  __metadata("design:type", Function),
@@ -41,6 +72,12 @@ __decorate([
41
72
  ExpressConfiguration = __decorate([
42
73
  (0, decorator_1.Configuration)({
43
74
  namespace: 'express',
75
+ imports: [session],
76
+ importConfigs: [
77
+ {
78
+ default: DefaultConfig,
79
+ },
80
+ ],
44
81
  })
45
82
  ], ExpressConfiguration);
46
83
  exports.ExpressConfiguration = ExpressConfiguration;
@@ -1,16 +1,12 @@
1
1
  /// <reference types="node" />
2
- import { BaseFramework, ContextMiddlewareManager, FunctionMiddleware, IMidwayBootstrapOptions, MiddlewareRespond, MidwayFrameworkType, ExceptionFilterManager } from '@midwayjs/core';
3
- import { RouterParamValue } from '@midwayjs/decorator';
2
+ import { BaseFramework, IMidwayBootstrapOptions, MiddlewareRespond, MidwayFrameworkType, RouterInfo } from '@midwayjs/core';
4
3
  import { IMidwayExpressApplication, IMidwayExpressConfigurationOptions, IMidwayExpressContext } from './interface';
5
4
  import type { IRouter, IRouterHandler, Response, NextFunction } from 'express';
6
5
  import { Server } from 'net';
7
6
  import { MidwayExpressContextLogger } from './logger';
8
- export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpressApplication, IMidwayExpressContext, IMidwayExpressConfigurationOptions> {
7
+ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpressApplication, IMidwayExpressContext, IMidwayExpressConfigurationOptions, Response, NextFunction> {
9
8
  app: IMidwayExpressApplication;
10
- private controllerIds;
11
9
  private server;
12
- protected middlewareManager: ContextMiddlewareManager<IMidwayExpressContext, Response<any, Record<string, any>>, NextFunction>;
13
- protected exceptionFilterManager: ExceptionFilterManager<IMidwayExpressContext, Response<any, Record<string, any>>, NextFunction>;
14
10
  private expressMiddlewareService;
15
11
  configure(): IMidwayExpressConfigurationOptions;
16
12
  applicationInitialize(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
@@ -18,27 +14,20 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
18
14
  getFrameworkType(): MidwayFrameworkType;
19
15
  /**
20
16
  * wrap controller string to middleware function
21
- * @param controllerMapping like FooController.index
22
- * @param routeArgsInfo
23
- * @param routerResponseData
24
17
  */
25
- generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): IRouterHandler<any>;
18
+ protected generateController(routeInfo: RouterInfo): IRouterHandler<any>;
26
19
  loadMidwayController(): Promise<void>;
27
- /**
28
- * @deprecated
29
- */
30
- generateMiddleware(middlewareId: string): Promise<FunctionMiddleware<IMidwayExpressContext, Response<any, Record<string, any>>, NextFunction>>;
31
20
  /**
32
21
  * @param routerOptions
33
22
  */
34
23
  protected createRouter(routerOptions: {
35
24
  sensitive: any;
36
25
  }): IRouter;
37
- private handlerWebMiddleware;
38
- getMiddleware<Response, NextFunction>(): Promise<MiddlewareRespond<IMidwayExpressContext, Response, NextFunction>>;
26
+ applyMiddleware<Response, NextFunction>(): Promise<MiddlewareRespond<IMidwayExpressContext, Response, NextFunction>>;
39
27
  beforeStop(): Promise<void>;
40
28
  getServer(): Server;
41
29
  getFrameworkName(): string;
42
30
  getDefaultContextLoggerClass(): typeof MidwayExpressContextLogger;
31
+ protected sendData(res: any, data: any): void;
43
32
  }
44
33
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -5,9 +5,6 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
6
  return c > 3 && r && Object.defineProperty(target, key, r), r;
7
7
  };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
8
  Object.defineProperty(exports, "__esModule", { value: true });
12
9
  exports.MidwayExpressFramework = void 0;
13
10
  const core_1 = require("@midwayjs/core");
@@ -15,29 +12,18 @@ const decorator_1 = require("@midwayjs/decorator");
15
12
  const express = require("express");
16
13
  const logger_1 = require("./logger");
17
14
  const middlewareService_1 = require("./middlewareService");
15
+ const util_1 = require("util");
16
+ const debug = (0, util_1.debuglog)('midway:debug');
18
17
  let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
19
- constructor() {
20
- super(...arguments);
21
- this.controllerIds = [];
22
- this.middlewareManager = new core_1.ContextMiddlewareManager();
23
- this.exceptionFilterManager = new core_1.ExceptionFilterManager();
24
- }
25
18
  configure() {
26
19
  return this.configService.getConfiguration('express');
27
20
  }
28
21
  async applicationInitialize(options) {
22
+ this.expressMiddlewareService = await this.applicationContext.getAsync(middlewareService_1.MidwayExpressMiddlewareService, [this.applicationContext]);
23
+ debug('[express]: create express app');
29
24
  this.app = express();
30
- this.defineApplicationProperties({
31
- generateController: (controllerMapping) => {
32
- return this.generateController(controllerMapping);
33
- },
34
- /**
35
- * @deprecated
36
- */
37
- generateMiddleware: async (middlewareId) => {
38
- return this.generateMiddleware(middlewareId);
39
- },
40
- });
25
+ debug('[express]: use root middleware');
26
+ // use root middleware
41
27
  this.app.use((req, res, next) => {
42
28
  const ctx = req;
43
29
  this.app.createAnonymousContext(ctx);
@@ -46,6 +32,68 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
46
32
  ctx.requestContext.registerObject('res', res);
47
33
  next();
48
34
  });
35
+ this.defineApplicationProperties();
36
+ // hack use method
37
+ this.app.originUse = this.app.use;
38
+ this.app.use = this.app.useMiddleware;
39
+ }
40
+ async run() {
41
+ var _a;
42
+ debug(`[express]: use middlewares = "${this.getMiddleware().getNames()}"`);
43
+ // restore use method
44
+ this.app.use = this.app.originUse;
45
+ // use global middleware
46
+ const globalMiddleware = await this.applyMiddleware();
47
+ debug('[express]: use and apply all framework and global middleware');
48
+ this.app.use(globalMiddleware);
49
+ debug('[express]: use user router middleware');
50
+ // load controller
51
+ await this.loadMidwayController();
52
+ debug('[express]: use 404 not found middleware');
53
+ // eslint-disable-next-line
54
+ this.app.use(function notFound(req, res, next) {
55
+ next(new core_1.httpError.NotFoundError());
56
+ });
57
+ debug('[express]: use global error handler middleware');
58
+ // use global error handler
59
+ this.app.use((err, req, res, next) => {
60
+ this.filterManager
61
+ .runErrorFilter(err, req, res, next)
62
+ .then(data => {
63
+ var _a, _b;
64
+ const { result, error } = data;
65
+ if (error) {
66
+ const status = (_b = (_a = error.status) !== null && _a !== void 0 ? _a : res.statusCode) !== null && _b !== void 0 ? _b : 500;
67
+ // 5xx
68
+ if (status >= 500) {
69
+ try {
70
+ req.logger.error(err);
71
+ }
72
+ catch (ex) {
73
+ this.logger.error(err);
74
+ this.logger.error(ex);
75
+ }
76
+ return;
77
+ }
78
+ // 4xx
79
+ try {
80
+ req.logger.warn(err);
81
+ }
82
+ catch (ex) {
83
+ this.logger.warn(err);
84
+ this.logger.error(ex);
85
+ }
86
+ res.status(status);
87
+ next(error);
88
+ }
89
+ else {
90
+ this.sendData(res, result);
91
+ }
92
+ })
93
+ .catch(err => {
94
+ next(err);
95
+ });
96
+ });
49
97
  // https config
50
98
  if (this.configurationOptions.key && this.configurationOptions.cert) {
51
99
  this.configurationOptions.key = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.key);
@@ -68,28 +116,10 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
68
116
  }
69
117
  // register httpServer to applicationContext
70
118
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
71
- }
72
- async run() {
73
- // use global middleware
74
- const globalMiddleware = await this.getMiddleware();
75
- this.app.use(globalMiddleware);
76
- // load controller
77
- await this.loadMidwayController();
78
- // use global error handler
79
- this.app.use(async (err, req, res, next) => {
80
- if (err) {
81
- const { result, error } = await this.exceptionFilterManager.run(err, req, res, next);
82
- if (error) {
83
- next(error);
84
- }
85
- else {
86
- res.send(result);
87
- }
88
- }
89
- });
90
- if (this.configurationOptions.port) {
119
+ const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
120
+ if (customPort) {
91
121
  new Promise(resolve => {
92
- const args = [this.configurationOptions.port];
122
+ const args = [customPort];
93
123
  if (this.configurationOptions.hostname) {
94
124
  args.push(this.configurationOptions.hostname);
95
125
  }
@@ -97,6 +127,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
97
127
  resolve();
98
128
  });
99
129
  this.server.listen(...args);
130
+ process.env.MIDWAY_HTTP_PORT = String(customPort);
100
131
  });
101
132
  }
102
133
  }
@@ -105,15 +136,11 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
105
136
  }
106
137
  /**
107
138
  * wrap controller string to middleware function
108
- * @param controllerMapping like FooController.index
109
- * @param routeArgsInfo
110
- * @param routerResponseData
111
139
  */
112
- generateController(controllerMapping, routeArgsInfo, routerResponseData) {
113
- const [controllerId, methodName] = controllerMapping.split('.');
114
- return async (req, res, next) => {
115
- const controller = await req.requestContext.getAsync(controllerId);
116
- const result = await controller[methodName].call(controller, req, res, next);
140
+ generateController(routeInfo) {
141
+ return (0, middlewareService_1.wrapAsyncHandler)(async (req, res, next) => {
142
+ const controller = await req.requestContext.getAsync(routeInfo.id);
143
+ const result = await controller[routeInfo.method].call(controller, req, res, next);
117
144
  if (res.headersSent) {
118
145
  // return when response send
119
146
  return;
@@ -122,8 +149,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
122
149
  res.status(204);
123
150
  }
124
151
  // implement response decorator
125
- if (Array.isArray(routerResponseData) && routerResponseData.length) {
126
- for (const routerRes of routerResponseData) {
152
+ if (Array.isArray(routeInfo.responseMetadata) &&
153
+ routeInfo.responseMetadata.length) {
154
+ for (const routerRes of routeInfo.responseMetadata) {
127
155
  switch (routerRes.type) {
128
156
  case decorator_1.WEB_RESPONSE_HTTP_CODE:
129
157
  res.status(routerRes.code);
@@ -140,64 +168,59 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
140
168
  }
141
169
  }
142
170
  }
143
- res.send(result);
144
- };
171
+ const { result: returnValue, error } = await this.filterManager.runResultFilter(result, req, res, next);
172
+ if (error) {
173
+ throw error;
174
+ }
175
+ this.sendData(res, returnValue);
176
+ });
145
177
  }
146
178
  async loadMidwayController() {
147
- const collector = new core_1.WebRouterCollector();
179
+ var _a, _b;
180
+ const collector = new core_1.WebRouterCollector('', {
181
+ globalPrefix: this.configurationOptions.globalPrefix,
182
+ });
148
183
  const routerTable = await collector.getRouterTable();
149
184
  const routerList = await collector.getRoutePriorityList();
150
185
  for (const routerInfo of routerList) {
151
186
  // bind controller first
152
187
  this.getApplicationContext().bindClass(routerInfo.routerModule);
153
- const providerId = routerInfo.controllerId;
154
- // controller id check
155
- if (this.controllerIds.indexOf(providerId) > -1) {
156
- throw new Error(`Controller identifier [${providerId}] already exists!`);
157
- }
158
- this.controllerIds.push(providerId);
159
- this.logger.debug(`Load Controller "${providerId}", prefix=${routerInfo.prefix}`);
188
+ this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
160
189
  // new router
161
190
  const newRouter = this.createRouter(routerInfo.routerOptions);
191
+ routerInfo.middleware = (_a = routerInfo.middleware) !== null && _a !== void 0 ? _a : [];
162
192
  // add router middleware
163
- await this.handlerWebMiddleware(routerInfo.middleware, (middlewareImpl) => {
164
- newRouter.use(middlewareImpl);
165
- });
193
+ if (routerInfo.middleware.length) {
194
+ const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
195
+ newRouter.use(routerMiddlewareFn);
196
+ }
166
197
  // add route
167
198
  const routes = routerTable.get(routerInfo.prefix);
168
199
  for (const routeInfo of routes) {
169
- // router middleware
170
- await this.handlerWebMiddleware(routeInfo.middleware, (middlewareImpl) => {
171
- newRouter.use(middlewareImpl);
172
- });
200
+ const routeMiddlewareList = [];
201
+ // routeInfo middleware
202
+ routeInfo.middleware = (_b = routeInfo.middleware) !== null && _b !== void 0 ? _b : [];
203
+ if (routeInfo.middleware.length) {
204
+ const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
205
+ routeMiddlewareList.push(routeMiddlewareFn);
206
+ }
173
207
  this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
174
208
  // apply controller from request context
175
- newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, this.generateController(routeInfo.handlerName, routeInfo.requestMetadata, routeInfo.responseMetadata));
209
+ newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
176
210
  }
177
211
  this.app.use(routerInfo.prefix, newRouter);
178
212
  }
179
213
  }
180
- /**
181
- * @deprecated
182
- */
183
- async generateMiddleware(middlewareId) {
184
- const mwIns = await this.getApplicationContext().getAsync(middlewareId);
185
- return mwIns.resolve();
186
- }
187
214
  /**
188
215
  * @param routerOptions
189
216
  */
190
217
  createRouter(routerOptions) {
191
218
  return express.Router({ caseSensitive: routerOptions.sensitive });
192
219
  }
193
- async handlerWebMiddleware(middlewares, handlerCallback) {
194
- const fn = await this.expressMiddlewareService.compose(middlewares);
195
- handlerCallback(fn);
196
- }
197
- async getMiddleware() {
220
+ async applyMiddleware() {
198
221
  if (!this.composeMiddleware) {
199
- this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager);
200
- await this.exceptionFilterManager.init(this.applicationContext);
222
+ this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager, this.app);
223
+ await this.filterManager.init(this.applicationContext);
201
224
  }
202
225
  return this.composeMiddleware;
203
226
  }
@@ -213,11 +236,15 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
213
236
  getDefaultContextLoggerClass() {
214
237
  return logger_1.MidwayExpressContextLogger;
215
238
  }
239
+ sendData(res, data) {
240
+ if (typeof data === 'number') {
241
+ res.status(res.statusCode).send('' + data);
242
+ }
243
+ else {
244
+ res.status(res.statusCode).send(data);
245
+ }
246
+ }
216
247
  };
217
- __decorate([
218
- (0, decorator_1.Inject)(),
219
- __metadata("design:type", middlewareService_1.MidwayExpressMiddlewareService)
220
- ], MidwayExpressFramework.prototype, "expressMiddlewareService", void 0);
221
248
  MidwayExpressFramework = __decorate([
222
249
  (0, decorator_1.Framework)()
223
250
  ], MidwayExpressFramework);
@@ -1,17 +1,29 @@
1
1
  /// <reference types="node" />
2
- import { IConfigurationOptions, IMiddleware, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
3
- import { Application as ExpressApplication, NextFunction, Request, Response } from 'express';
4
- import { RouterParamValue } from "@midwayjs/decorator";
2
+ import { CommonMiddlewareUnion, ContextMiddlewareManager, IConfigurationOptions, IMiddleware, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
3
+ import { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request, Response } from 'express';
4
+ import { Options, OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';
5
5
  export declare type IMidwayExpressContext = IMidwayContext<Request>;
6
- export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, NextFunction>;
7
- export declare type IMidwayExpressApplication = IMidwayApplication<IMidwayExpressContext, ExpressApplication & {
8
- generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): IMidwayExpressMiddleware;
6
+ /**
7
+ * @deprecated use IMidwayExpressContext
8
+ */
9
+ export declare type IMidwayExpressRequest = IMidwayExpressContext;
10
+ export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, ExpressNextFunction>;
11
+ export interface IMidwayExpressApplication extends IMidwayApplication<IMidwayExpressContext, ExpressApplication> {
9
12
  /**
10
- * @deprecated
13
+ * add global middleware to app
14
+ * @param Middleware
11
15
  */
12
- generateMiddleware(middlewareId: string): Promise<IMidwayExpressMiddleware>;
13
- }>;
16
+ useMiddleware<Response, NextFunction>(Middleware: CommonMiddlewareUnion<IMidwayExpressContext, Response, NextFunction>): void;
17
+ /**
18
+ * get global middleware
19
+ */
20
+ getMiddleware<Response, NextFunction>(): ContextMiddlewareManager<IMidwayExpressContext, Response, NextFunction>;
21
+ }
14
22
  export interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {
23
+ /**
24
+ * session or cookie secret key
25
+ */
26
+ keys?: string | string[];
15
27
  /**
16
28
  * application http port
17
29
  */
@@ -36,8 +48,33 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
36
48
  * http2 support
37
49
  */
38
50
  http2?: boolean;
51
+ /**
52
+ * http global prefix
53
+ */
54
+ globalPrefix?: string;
39
55
  }
40
56
  export declare type Application = IMidwayExpressApplication;
57
+ export declare type NextFunction = ExpressNextFunction;
41
58
  export interface Context extends IMidwayExpressContext {
42
59
  }
60
+ declare module '@midwayjs/core/dist/interface' {
61
+ interface MidwayConfig {
62
+ express?: IMidwayExpressConfigurationOptions;
63
+ bodyParser?: {
64
+ enable?: boolean;
65
+ json?: OptionsJson & {
66
+ enable?: boolean;
67
+ };
68
+ raw?: Options & {
69
+ enable?: boolean;
70
+ };
71
+ text?: OptionsText & {
72
+ enable?: boolean;
73
+ };
74
+ urlencoded?: OptionsUrlencoded & {
75
+ enable?: boolean;
76
+ };
77
+ };
78
+ }
79
+ }
43
80
  //# sourceMappingURL=interface.d.ts.map
@@ -1,13 +1,14 @@
1
- import { IMidwayContainer, CommonMiddleware } from '@midwayjs/core';
2
- import { IMidwayExpressContext } from './interface';
1
+ import { IMidwayContainer, CommonMiddleware, FunctionMiddleware } from '@midwayjs/core';
2
+ import { IMidwayExpressContext, 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<IMidwayExpressContext, Response, NextFunction> | string>, app: Application, name?: string): Promise<{
9
+ (req: IMidwayExpressContext, res: Response, nextFunction: NextFunction): any;
9
10
  _name: string;
10
11
  }>;
11
12
  }
12
- export declare function pathMatching(options: any): (ctx?: any) => any;
13
+ export declare function wrapMiddleware(mw: FunctionMiddleware<any, any, any>, options: any): (context: any, next: any, options?: any) => any;
13
14
  //# sourceMappingURL=middlewareService.d.ts.map
@@ -9,14 +9,27 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.pathMatching = exports.MidwayExpressMiddlewareService = void 0;
12
+ exports.wrapMiddleware = exports.MidwayExpressMiddlewareService = exports.wrapAsyncHandler = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const core_1 = require("@midwayjs/core");
15
+ function wrapAsyncHandler(fn) {
16
+ if ((0, decorator_1.isAsyncFunction)(fn)) {
17
+ return (req, res, next) => {
18
+ return fn(req, res, next).catch(err => {
19
+ next(err);
20
+ });
21
+ };
22
+ }
23
+ else {
24
+ return fn;
25
+ }
26
+ }
27
+ exports.wrapAsyncHandler = wrapAsyncHandler;
15
28
  let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
16
29
  constructor(applicationContext) {
17
30
  this.applicationContext = applicationContext;
18
31
  }
19
- async compose(middleware, name) {
32
+ async compose(middleware, app, name) {
20
33
  if (!Array.isArray(middleware)) {
21
34
  throw new core_1.MidwayCommonError('Middleware stack must be an array');
22
35
  }
@@ -29,7 +42,9 @@ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
29
42
  }
30
43
  const classMiddleware = await this.applicationContext.getAsync(fn);
31
44
  if (classMiddleware) {
32
- fn = classMiddleware.resolve();
45
+ fn = classMiddleware.resolve(app);
46
+ // wrap async middleware
47
+ fn = wrapAsyncHandler(fn);
33
48
  if (!classMiddleware.match && !classMiddleware.ignore) {
34
49
  fn._name = classMiddleware.constructor.name;
35
50
  // just got fn
@@ -38,7 +53,7 @@ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
38
53
  else {
39
54
  // wrap ignore and match
40
55
  const mw = fn;
41
- const match = pathMatching({
56
+ const match = (0, core_1.pathMatching)({
42
57
  match: classMiddleware.match,
43
58
  ignore: classMiddleware.ignore,
44
59
  });
@@ -56,16 +71,36 @@ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
56
71
  }
57
72
  }
58
73
  else {
74
+ // wrap async middleware
75
+ fn = wrapAsyncHandler(fn);
59
76
  newMiddlewareArr.push(fn);
60
77
  }
61
78
  }
62
- const composeFn = (req, res, next) => {
63
- (function iter(i, max) {
64
- if (i === max) {
65
- return next();
79
+ const composeFn = (req, res, nextFunction) => {
80
+ let index = -1;
81
+ function dispatch(pos, err) {
82
+ const handler = newMiddlewareArr[pos];
83
+ index = pos;
84
+ if (err || index === newMiddlewareArr.length) {
85
+ return nextFunction(err);
86
+ }
87
+ function next(err) {
88
+ if (pos < index) {
89
+ throw new TypeError('`next()` called multiple times');
90
+ }
91
+ return dispatch(pos + 1, err);
92
+ }
93
+ try {
94
+ return handler(req, res, next);
66
95
  }
67
- newMiddlewareArr[i](req, res, iter.bind(this, i + 1, max));
68
- })(0, newMiddlewareArr.length);
96
+ catch (err) {
97
+ // Avoid future errors that could diverge stack execution.
98
+ if (index > pos)
99
+ throw err;
100
+ return next(err);
101
+ }
102
+ }
103
+ return dispatch(0);
69
104
  };
70
105
  if (name) {
71
106
  composeFn._name = name;
@@ -79,41 +114,21 @@ MidwayExpressMiddlewareService = __decorate([
79
114
  __metadata("design:paramtypes", [Object])
80
115
  ], MidwayExpressMiddlewareService);
81
116
  exports.MidwayExpressMiddlewareService = MidwayExpressMiddlewareService;
82
- function pathMatching(options) {
83
- options = options || {};
84
- if (options.match && options.ignore)
85
- throw new core_1.MidwayCommonError('options.match and options.ignore can not both present');
117
+ function wrapMiddleware(mw, options) {
118
+ // support options.enable
119
+ if (options.enable === false)
120
+ return null;
121
+ // support options.match and options.ignore
86
122
  if (!options.match && !options.ignore)
87
- return () => true;
88
- const matchFn = options.match
89
- ? toPathMatch(options.match)
90
- : toPathMatch(options.ignore);
91
- return function pathMatch(ctx) {
92
- const matched = matchFn(ctx);
93
- return options.match ? matched : !matched;
123
+ return mw;
124
+ const match = (0, core_1.pathMatching)(options);
125
+ const fn = (req, res, next) => {
126
+ if (!match(req))
127
+ return next();
128
+ return mw(req, res, next);
94
129
  };
130
+ fn._name = mw._name + 'middlewareWrapper';
131
+ return fn;
95
132
  }
96
- exports.pathMatching = pathMatching;
97
- function toPathMatch(pattern) {
98
- if (typeof pattern === 'string') {
99
- const reg = (0, core_1.pathToRegexp)(pattern, [], { end: false });
100
- if (reg.global)
101
- reg.lastIndex = 0;
102
- return ctx => reg.test(ctx.path);
103
- }
104
- if (pattern instanceof RegExp) {
105
- return ctx => {
106
- if (pattern.global)
107
- pattern.lastIndex = 0;
108
- return pattern.test(ctx.path);
109
- };
110
- }
111
- if (typeof pattern === 'function')
112
- return pattern;
113
- if (Array.isArray(pattern)) {
114
- const matchs = pattern.map(item => toPathMatch(item));
115
- return ctx => matchs.some(match => match(ctx));
116
- }
117
- throw new core_1.MidwayCommonError('match/ignore pattern must be RegExp, Array or String, but got ' + pattern);
118
- }
133
+ exports.wrapMiddleware = wrapMiddleware;
119
134
  //# sourceMappingURL=middlewareService.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/express",
3
- "version": "3.0.0-beta.1",
3
+ "version": "3.0.0-beta.13",
4
4
  "description": "Midway Web Framework for Express",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -23,14 +23,18 @@
23
23
  ],
24
24
  "license": "MIT",
25
25
  "devDependencies": {
26
- "@midwayjs/decorator": "^3.0.0-beta.1",
27
- "@midwayjs/mock": "^3.0.0-beta.1",
26
+ "@midwayjs/decorator": "^3.0.0-beta.13",
27
+ "@midwayjs/logger": "^3.0.0-beta.13",
28
+ "@midwayjs/mock": "^3.0.0-beta.13",
29
+ "@types/body-parser": "^1.19.2",
28
30
  "@types/express": "^4.17.8",
29
31
  "fs-extra": "^8.0.1"
30
32
  },
31
33
  "dependencies": {
32
- "@midwayjs/core": "^3.0.0-beta.1",
33
- "@midwayjs/logger": "^3.0.0-beta.1",
34
+ "@midwayjs/core": "^3.0.0-beta.13",
35
+ "@midwayjs/express-session": "^3.0.0-beta.13",
36
+ "body-parser": "^1.19.0",
37
+ "cookie-parser": "^1.4.6",
34
38
  "express": "^4.17.1"
35
39
  },
36
40
  "author": "Harry Chen <czy88840616@gmail.com>",
@@ -41,5 +45,5 @@
41
45
  "engines": {
42
46
  "node": ">=12"
43
47
  },
44
- "gitHead": "72e4d20c678e65a5440c4e9a6d3b70046daa497c"
48
+ "gitHead": "d3c47770fee9dce33a8d148882173fd7782864ad"
45
49
  }