@midwayjs/express 3.0.0-alpha.6 → 3.0.0-beta.11

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,116 @@
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.11](https://github.com/midwayjs/midway/compare/v3.0.0-beta.10...v3.0.0-beta.11) (2021-12-21)
7
+
8
+ **Note:** Version bump only for package @midwayjs/express
9
+
10
+
11
+
12
+
13
+
14
+ # [3.0.0-beta.10](https://github.com/midwayjs/midway/compare/v3.0.0-beta.9...v3.0.0-beta.10) (2021-12-20)
15
+
16
+
17
+ ### Features
18
+
19
+ * 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))
20
+ * implement i18n for validate ([#1426](https://github.com/midwayjs/midway/issues/1426)) ([4c7ed2f](https://github.com/midwayjs/midway/commit/4c7ed2ff2e7ccf10f88f62abad230f92f5e76b97))
21
+
22
+
23
+
24
+
25
+
26
+ # [3.0.0-beta.9](https://github.com/midwayjs/midway/compare/v3.0.0-beta.8...v3.0.0-beta.9) (2021-12-09)
27
+
28
+ **Note:** Version bump only for package @midwayjs/express
29
+
30
+
31
+
32
+
33
+
34
+ # [3.0.0-beta.8](https://github.com/midwayjs/midway/compare/v3.0.0-beta.7...v3.0.0-beta.8) (2021-12-08)
35
+
36
+
37
+ ### Bug Fixes
38
+
39
+ * 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))
40
+ * typeorm EntityView missing connectionName ([#1403](https://github.com/midwayjs/midway/issues/1403)) ([30b2b37](https://github.com/midwayjs/midway/commit/30b2b3711db485cb85d825d56aeabf53b1374cae))
41
+
42
+
43
+
44
+
45
+
46
+ # [3.0.0-beta.7](https://github.com/midwayjs/midway/compare/v3.0.0-beta.6...v3.0.0-beta.7) (2021-12-03)
47
+
48
+ **Note:** Version bump only for package @midwayjs/express
49
+
50
+
51
+
52
+
53
+
54
+ # [3.0.0-beta.6](https://github.com/midwayjs/midway/compare/v3.0.0-beta.5...v3.0.0-beta.6) (2021-11-26)
55
+
56
+
57
+ ### Bug Fixes
58
+
59
+ * class transformer method missing ([#1387](https://github.com/midwayjs/midway/issues/1387)) ([074e839](https://github.com/midwayjs/midway/commit/074e8393598dc95e2742f735df75a2191c5fe25d))
60
+
61
+
62
+
63
+
64
+
65
+ # [3.0.0-beta.5](https://github.com/midwayjs/midway/compare/v3.0.0-beta.4...v3.0.0-beta.5) (2021-11-25)
66
+
67
+ **Note:** Version bump only for package @midwayjs/express
68
+
69
+
70
+
71
+
72
+
73
+ # [3.0.0-beta.4](https://github.com/midwayjs/midway/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-11-24)
74
+
75
+
76
+ ### Features
77
+
78
+ * add i18n ([#1375](https://github.com/midwayjs/midway/issues/1375)) ([bffefe0](https://github.com/midwayjs/midway/commit/bffefe07afe45777d49b5a76b9ab17fc2b9d9a55))
79
+ * auto transform args to type ([#1372](https://github.com/midwayjs/midway/issues/1372)) ([bb3f7d2](https://github.com/midwayjs/midway/commit/bb3f7d2028a034e1926d9df554849332354c3762))
80
+ * support global prefix url ([#1371](https://github.com/midwayjs/midway/issues/1371)) ([cc5fe44](https://github.com/midwayjs/midway/commit/cc5fe44e1d221590562dc71e1f33ae96093e0da7))
81
+
82
+
83
+
84
+
85
+
86
+ # [3.0.0-beta.3](https://github.com/midwayjs/midway/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-11-18)
87
+
88
+
89
+ ### Features
90
+
91
+ * add component and framework config definition ([#1367](https://github.com/midwayjs/midway/issues/1367)) ([b2fe615](https://github.com/midwayjs/midway/commit/b2fe6157f99659471ff1333eca0b86bb889f61a3))
92
+
93
+
94
+
95
+
96
+
97
+ # [3.0.0-beta.2](https://github.com/midwayjs/midway/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-11-16)
98
+
99
+ **Note:** Version bump only for package @midwayjs/express
100
+
101
+
102
+
103
+
104
+
105
+ # [3.0.0-beta.1](https://github.com/midwayjs/midway/compare/v2.12.4...v3.0.0-beta.1) (2021-11-14)
106
+
107
+
108
+ ### Features
109
+
110
+ * add http2 support ([#1242](https://github.com/midwayjs/midway/issues/1242)) ([6cda27e](https://github.com/midwayjs/midway/commit/6cda27e9e22689e46ace543326b43ae21b134911))
111
+
112
+
113
+
114
+
115
+
6
116
  ## [2.12.3](https://github.com/midwayjs/midway/compare/v2.12.2...v2.12.3) (2021-08-09)
7
117
 
8
118
  **Note:** Version bump only for package @midwayjs/express
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
@@ -0,0 +1,10 @@
1
+ import { MidwayConfigService, MidwayDecoratorService } from '@midwayjs/core';
2
+ import { MidwayExpressFramework } from './framework';
3
+ export declare class ExpressConfiguration {
4
+ decoratorService: MidwayDecoratorService;
5
+ expressFramework: MidwayExpressFramework;
6
+ configService: MidwayConfigService;
7
+ init(): void;
8
+ onReady(): Promise<void>;
9
+ }
10
+ //# sourceMappingURL=configuration.d.ts.map
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
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
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ExpressConfiguration = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
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");
20
+ let ExpressConfiguration = class ExpressConfiguration {
21
+ init() {
22
+ this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
23
+ return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData, options.originParamType)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
24
+ });
25
+ }
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
+ }
53
+ };
54
+ __decorate([
55
+ (0, decorator_1.Inject)(),
56
+ __metadata("design:type", core_1.MidwayDecoratorService)
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);
66
+ __decorate([
67
+ (0, decorator_1.Init)(),
68
+ __metadata("design:type", Function),
69
+ __metadata("design:paramtypes", []),
70
+ __metadata("design:returntype", void 0)
71
+ ], ExpressConfiguration.prototype, "init", null);
72
+ ExpressConfiguration = __decorate([
73
+ (0, decorator_1.Configuration)({
74
+ namespace: 'express',
75
+ imports: [session],
76
+ importConfigs: [
77
+ {
78
+ default: DefaultConfig,
79
+ },
80
+ ],
81
+ })
82
+ ], ExpressConfiguration);
83
+ exports.ExpressConfiguration = ExpressConfiguration;
84
+ //# sourceMappingURL=configuration.js.map
@@ -1,42 +1,33 @@
1
1
  /// <reference types="node" />
2
- import { BaseFramework, IMidwayBootstrapOptions, MidwayFrameworkType } 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
- import type { IRouter, IRouterHandler } from 'express';
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
- prioritySortRouters: Array<{
12
- priority: number;
13
- router: IRouter;
14
- prefix: string;
15
- }>;
16
9
  private server;
10
+ private expressMiddlewareService;
11
+ configure(): IMidwayExpressConfigurationOptions;
17
12
  applicationInitialize(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
18
- protected afterContainerReady(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
19
13
  run(): Promise<void>;
20
14
  getFrameworkType(): MidwayFrameworkType;
21
15
  /**
22
16
  * wrap controller string to middleware function
23
- * @param controllerMapping like FooController.index
24
- * @param routeArgsInfo
25
- * @param routerResponseData
26
17
  */
27
- generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): IRouterHandler<any>;
18
+ protected generateController(routeInfo: RouterInfo): IRouterHandler<any>;
28
19
  loadMidwayController(): Promise<void>;
29
- generateMiddleware(middlewareId: string): Promise<import("./interface").Middleware>;
30
20
  /**
31
- * @param controllerOption
21
+ * @param routerOptions
32
22
  */
33
23
  protected createRouter(routerOptions: {
34
24
  sensitive: any;
35
25
  }): IRouter;
36
- private handlerWebMiddleware;
26
+ applyMiddleware<Response, NextFunction>(): Promise<MiddlewareRespond<IMidwayExpressContext, Response, NextFunction>>;
37
27
  beforeStop(): Promise<void>;
38
28
  getServer(): Server;
39
29
  getFrameworkName(): string;
40
30
  getDefaultContextLoggerClass(): typeof MidwayExpressContextLogger;
31
+ protected sendData(res: any, data: any): void;
41
32
  }
42
33
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -1,52 +1,76 @@
1
1
  "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
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
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
2
8
  Object.defineProperty(exports, "__esModule", { value: true });
3
9
  exports.MidwayExpressFramework = void 0;
4
10
  const core_1 = require("@midwayjs/core");
5
11
  const decorator_1 = require("@midwayjs/decorator");
6
12
  const express = require("express");
7
13
  const logger_1 = require("./logger");
8
- class MidwayExpressFramework extends core_1.BaseFramework {
9
- constructor() {
10
- super(...arguments);
11
- this.controllerIds = [];
12
- this.prioritySortRouters = [];
14
+ const middlewareService_1 = require("./middlewareService");
15
+ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
16
+ configure() {
17
+ return this.configService.getConfiguration('express');
13
18
  }
14
19
  async applicationInitialize(options) {
20
+ this.expressMiddlewareService = await this.applicationContext.getAsync(middlewareService_1.MidwayExpressMiddlewareService, [this.applicationContext]);
15
21
  this.app = express();
16
- this.defineApplicationProperties({
17
- generateController: (controllerMapping) => {
18
- return this.generateController(controllerMapping);
19
- },
20
- generateMiddleware: async (middlewareId) => {
21
- return this.generateMiddleware(middlewareId);
22
- },
23
- });
24
22
  this.app.use((req, res, next) => {
25
- const ctx = { req, res };
23
+ const ctx = req;
26
24
  this.app.createAnonymousContext(ctx);
27
25
  req.requestContext = ctx.requestContext;
28
26
  ctx.requestContext.registerObject('req', req);
29
27
  ctx.requestContext.registerObject('res', res);
30
28
  next();
31
29
  });
30
+ }
31
+ async run() {
32
+ var _a;
33
+ // use global middleware
34
+ const globalMiddleware = await this.applyMiddleware();
35
+ this.app.use(globalMiddleware);
36
+ // load controller
37
+ await this.loadMidwayController();
38
+ // 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);
42
+ if (error) {
43
+ next(error);
44
+ }
45
+ else {
46
+ this.sendData(res, result);
47
+ }
48
+ }
49
+ });
32
50
  // https config
33
51
  if (this.configurationOptions.key && this.configurationOptions.cert) {
34
52
  this.configurationOptions.key = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.key);
35
53
  this.configurationOptions.cert = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.cert);
36
54
  this.configurationOptions.ca = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.ca);
37
- this.server = require('https').createServer(this.configurationOptions, this.app);
55
+ if (this.configurationOptions.http2) {
56
+ this.server = require('http2').createSecureServer(this.configurationOptions, this.app);
57
+ }
58
+ else {
59
+ this.server = require('https').createServer(this.configurationOptions, this.app);
60
+ }
38
61
  }
39
62
  else {
40
- this.server = require('http').createServer(this.app);
63
+ if (this.configurationOptions.http2) {
64
+ this.server = require('http2').createServer(this.app);
65
+ }
66
+ else {
67
+ this.server = require('http').createServer(this.app);
68
+ }
41
69
  }
42
70
  // register httpServer to applicationContext
43
71
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
44
- }
45
- async afterContainerReady(options) {
46
- await this.loadMidwayController();
47
- }
48
- async run() {
49
- if (this.configurationOptions.port) {
72
+ const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
73
+ if (customPort) {
50
74
  new Promise(resolve => {
51
75
  const args = [this.configurationOptions.port];
52
76
  if (this.configurationOptions.hostname) {
@@ -56,6 +80,7 @@ class MidwayExpressFramework extends core_1.BaseFramework {
56
80
  resolve();
57
81
  });
58
82
  this.server.listen(...args);
83
+ process.env.MIDWAY_HTTP_PORT = String(customPort);
59
84
  });
60
85
  }
61
86
  }
@@ -64,22 +89,18 @@ class MidwayExpressFramework extends core_1.BaseFramework {
64
89
  }
65
90
  /**
66
91
  * wrap controller string to middleware function
67
- * @param controllerMapping like FooController.index
68
- * @param routeArgsInfo
69
- * @param routerResponseData
70
92
  */
71
- generateController(controllerMapping, routeArgsInfo, routerResponseData) {
72
- const [controllerId, methodName] = controllerMapping.split('.');
93
+ generateController(routeInfo) {
73
94
  return async (req, res, next) => {
74
- const args = [req, res, next];
75
- if (Array.isArray(routeArgsInfo)) {
76
- await Promise.all(routeArgsInfo.map(async ({ index, type, propertyData }) => {
77
- args[index] = await core_1.extractExpressLikeValue(type, propertyData)(req, res, next);
78
- }));
95
+ const controller = await req.requestContext.getAsync(routeInfo.id);
96
+ let result;
97
+ try {
98
+ result = await controller[routeInfo.method].call(controller, req, res, next);
99
+ }
100
+ catch (err) {
101
+ next(err);
102
+ return;
79
103
  }
80
- const controller = await req.requestContext.getAsync(controllerId);
81
- // eslint-disable-next-line prefer-spread
82
- const result = await controller[methodName].apply(controller, args);
83
104
  if (res.headersSent) {
84
105
  // return when response send
85
106
  return;
@@ -88,8 +109,9 @@ class MidwayExpressFramework extends core_1.BaseFramework {
88
109
  res.status(204);
89
110
  }
90
111
  // implement response decorator
91
- if (Array.isArray(routerResponseData) && routerResponseData.length) {
92
- for (const routerRes of routerResponseData) {
112
+ if (Array.isArray(routeInfo.responseMetadata) &&
113
+ routeInfo.responseMetadata.length) {
114
+ for (const routerRes of routeInfo.responseMetadata) {
93
115
  switch (routerRes.type) {
94
116
  case decorator_1.WEB_RESPONSE_HTTP_CODE:
95
117
  res.status(routerRes.code);
@@ -106,66 +128,58 @@ class MidwayExpressFramework extends core_1.BaseFramework {
106
128
  }
107
129
  }
108
130
  }
109
- res.send(result);
131
+ const { result: returnValue, error } = await this.filterManager.runResultFilter(result, req, res, next);
132
+ if (error) {
133
+ throw error;
134
+ }
135
+ this.sendData(res, returnValue);
110
136
  };
111
137
  }
112
138
  async loadMidwayController() {
113
- const collector = new core_1.WebRouterCollector();
139
+ const collector = new core_1.WebRouterCollector('', {
140
+ globalPrefix: this.configurationOptions.globalPrefix,
141
+ });
114
142
  const routerTable = await collector.getRouterTable();
115
143
  const routerList = await collector.getRoutePriorityList();
116
144
  for (const routerInfo of routerList) {
117
- const providerId = routerInfo.controllerId;
118
- // controller id check
119
- if (this.controllerIds.indexOf(providerId) > -1) {
120
- throw new Error(`Controller identifier [${providerId}] already exists!`);
121
- }
122
- this.controllerIds.push(providerId);
123
- this.logger.debug(`Load Controller "${providerId}", prefix=${routerInfo.prefix}`);
145
+ // bind controller first
146
+ this.getApplicationContext().bindClass(routerInfo.routerModule);
147
+ this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
124
148
  // new router
125
149
  const newRouter = this.createRouter(routerInfo.routerOptions);
126
150
  // add router middleware
127
- await this.handlerWebMiddleware(routerInfo.middleware, (middlewareImpl) => {
128
- newRouter.use(middlewareImpl);
129
- });
151
+ if (routerInfo.middleware.length) {
152
+ const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
153
+ newRouter.use(routerMiddlewareFn);
154
+ }
130
155
  // add route
131
156
  const routes = routerTable.get(routerInfo.prefix);
132
157
  for (const routeInfo of routes) {
133
- // router middleware
134
- await this.handlerWebMiddleware(routeInfo.middleware, (middlewareImpl) => {
135
- newRouter.use(middlewareImpl);
136
- });
158
+ const routeMiddlewareList = [];
159
+ // routeInfo middleware
160
+ if (routeInfo.middleware.length) {
161
+ const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
162
+ routeMiddlewareList.push(routeMiddlewareFn);
163
+ }
137
164
  this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
138
165
  // apply controller from request context
139
- newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, this.generateController(routeInfo.handlerName, routeInfo.requestMetadata, routeInfo.responseMetadata));
166
+ newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
140
167
  }
141
168
  this.app.use(routerInfo.prefix, newRouter);
142
169
  }
143
170
  }
144
- async generateMiddleware(middlewareId) {
145
- const mwIns = await this.getApplicationContext().getAsync(middlewareId);
146
- return mwIns.resolve();
147
- }
148
171
  /**
149
- * @param controllerOption
172
+ * @param routerOptions
150
173
  */
151
174
  createRouter(routerOptions) {
152
175
  return express.Router({ caseSensitive: routerOptions.sensitive });
153
176
  }
154
- async handlerWebMiddleware(middlewares, handlerCallback) {
155
- if (middlewares && middlewares.length) {
156
- for (const middleware of middlewares) {
157
- if (typeof middleware === 'function') {
158
- // web function middleware
159
- handlerCallback(middleware);
160
- }
161
- else {
162
- const middlewareImpl = await this.getApplicationContext().getAsync(middleware);
163
- if (middlewareImpl && typeof middlewareImpl.resolve === 'function') {
164
- handlerCallback(middlewareImpl.resolve());
165
- }
166
- }
167
- }
177
+ async applyMiddleware() {
178
+ if (!this.composeMiddleware) {
179
+ this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager, this.app);
180
+ await this.filterManager.init(this.applicationContext);
168
181
  }
182
+ return this.composeMiddleware;
169
183
  }
170
184
  async beforeStop() {
171
185
  this.server.close();
@@ -179,6 +193,17 @@ class MidwayExpressFramework extends core_1.BaseFramework {
179
193
  getDefaultContextLoggerClass() {
180
194
  return logger_1.MidwayExpressContextLogger;
181
195
  }
182
- }
196
+ sendData(res, data) {
197
+ if (typeof data === 'number') {
198
+ res.status(res.statusCode).send('' + data);
199
+ }
200
+ else {
201
+ res.status(res.statusCode).send(data);
202
+ }
203
+ }
204
+ };
205
+ MidwayExpressFramework = __decorate([
206
+ (0, decorator_1.Framework)()
207
+ ], MidwayExpressFramework);
183
208
  exports.MidwayExpressFramework = MidwayExpressFramework;
184
209
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export * from './interface';
2
2
  export { MidwayExpressFramework as Framework } from './framework';
3
+ export { ExpressConfiguration as Configuration } from './configuration';
4
+ export * from './middlewareService';
5
+ export * from './logger';
3
6
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -10,8 +10,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.Framework = void 0;
13
+ exports.Configuration = exports.Framework = void 0;
14
14
  __exportStar(require("./interface"), exports);
15
15
  var framework_1 = require("./framework");
16
16
  Object.defineProperty(exports, "Framework", { enumerable: true, get: function () { return framework_1.MidwayExpressFramework; } });
17
+ var configuration_1 = require("./configuration");
18
+ Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.ExpressConfiguration; } });
19
+ __exportStar(require("./middlewareService"), exports);
20
+ __exportStar(require("./logger"), exports);
17
21
  //# sourceMappingURL=index.js.map
@@ -1,28 +1,29 @@
1
1
  /// <reference types="node" />
2
- import { IConfigurationOptions, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
3
- import { Application as ExpressApplication, Request, Response, RequestHandler, NextFunction } 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
+ export declare type IMidwayExpressContext = IMidwayContext<Request>;
5
6
  /**
6
- * @deprecated use Request from express
7
+ * @deprecated use IMidwayExpressContext
7
8
  */
8
- export declare type IMidwayExpressRequest = Request;
9
- /**
10
- * @deprecated use Response from express
11
- */
12
- export declare type IMidwayExpressResponse = Response;
13
- /**
14
- * @deprecated use NextFunction from express
15
- */
16
- export declare type IMidwayExpressNext = NextFunction;
17
- export declare type IMidwayExpressContext = IMidwayContext<{
18
- req: Request;
19
- res: Response;
20
- }>;
21
- export declare type IMidwayExpressApplication = IMidwayApplication<IMidwayExpressContext, ExpressApplication & {
22
- generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): Middleware;
23
- generateMiddleware(middlewareId: string): Promise<Middleware>;
24
- }>;
9
+ export declare type IMidwayExpressRequest = IMidwayExpressContext;
10
+ export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, ExpressNextFunction>;
11
+ export interface IMidwayExpressApplication extends IMidwayApplication<IMidwayExpressContext, ExpressApplication> {
12
+ /**
13
+ * add global middleware to app
14
+ * @param Middleware
15
+ */
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
+ }
25
22
  export interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {
23
+ /**
24
+ * session or cookie secret key
25
+ */
26
+ keys?: string | string[];
26
27
  /**
27
28
  * application http port
28
29
  */
@@ -43,13 +44,37 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
43
44
  * https ca
44
45
  */
45
46
  ca?: string | Buffer | Array<string | Buffer>;
46
- }
47
- export declare type MiddlewareParamArray = RequestHandler[];
48
- export declare type Middleware = RequestHandler;
49
- export interface IWebMiddleware {
50
- resolve(): Middleware;
47
+ /**
48
+ * http2 support
49
+ */
50
+ http2?: boolean;
51
+ /**
52
+ * http global prefix
53
+ */
54
+ globalPrefix?: string;
51
55
  }
52
56
  export declare type Application = IMidwayExpressApplication;
57
+ export declare type NextFunction = ExpressNextFunction;
53
58
  export interface Context extends IMidwayExpressContext {
54
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
+ }
55
80
  //# sourceMappingURL=interface.d.ts.map
package/dist/logger.js CHANGED
@@ -5,7 +5,7 @@ const logger_1 = require("@midwayjs/logger");
5
5
  class MidwayExpressContextLogger extends logger_1.MidwayContextLogger {
6
6
  formatContextLabel() {
7
7
  var _a;
8
- const req = this.ctx.req;
8
+ const req = this.ctx;
9
9
  // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
10
10
  const userId = ((_a = req === null || req === void 0 ? void 0 : req['session']) === null || _a === void 0 ? void 0 : _a['userId']) || '-';
11
11
  const traceId = '-';
@@ -0,0 +1,13 @@
1
+ import { IMidwayContainer, CommonMiddleware, FunctionMiddleware } from '@midwayjs/core';
2
+ import { IMidwayExpressContext, Application } from './interface';
3
+ import { NextFunction, Response } from 'express';
4
+ export declare class MidwayExpressMiddlewareService {
5
+ readonly applicationContext: IMidwayContainer;
6
+ constructor(applicationContext: IMidwayContainer);
7
+ compose(middleware: Array<CommonMiddleware<IMidwayExpressContext, Response, NextFunction> | string>, app: Application, name?: string): Promise<{
8
+ (req: IMidwayExpressContext, res: Response, next: NextFunction): void;
9
+ _name: string;
10
+ }>;
11
+ }
12
+ export declare function wrapMiddleware(mw: FunctionMiddleware<any, any, any>, options: any): (context: any, next: any, options?: any) => any;
13
+ //# sourceMappingURL=middlewareService.d.ts.map
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
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
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.wrapMiddleware = exports.MidwayExpressMiddlewareService = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ const core_1 = require("@midwayjs/core");
15
+ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
16
+ constructor(applicationContext) {
17
+ this.applicationContext = applicationContext;
18
+ }
19
+ async compose(middleware, app, name) {
20
+ if (!Array.isArray(middleware)) {
21
+ throw new core_1.MidwayCommonError('Middleware stack must be an array');
22
+ }
23
+ const newMiddlewareArr = [];
24
+ for (let fn of middleware) {
25
+ if ((0, decorator_1.isClass)(fn) || typeof fn === 'string') {
26
+ if (typeof fn === 'string' &&
27
+ !this.applicationContext.hasDefinition(fn)) {
28
+ throw new core_1.MidwayCommonError('Middleware definition not found in midway container');
29
+ }
30
+ const classMiddleware = await this.applicationContext.getAsync(fn);
31
+ if (classMiddleware) {
32
+ fn = classMiddleware.resolve(app);
33
+ if (!classMiddleware.match && !classMiddleware.ignore) {
34
+ fn._name = classMiddleware.constructor.name;
35
+ // just got fn
36
+ newMiddlewareArr.push(fn);
37
+ }
38
+ else {
39
+ // wrap ignore and match
40
+ const mw = fn;
41
+ const match = (0, core_1.pathMatching)({
42
+ match: classMiddleware.match,
43
+ ignore: classMiddleware.ignore,
44
+ });
45
+ fn = (req, res, next) => {
46
+ if (!match(req))
47
+ return next();
48
+ return mw(req, res, next);
49
+ };
50
+ fn._name = classMiddleware.constructor.name;
51
+ newMiddlewareArr.push(fn);
52
+ }
53
+ }
54
+ else {
55
+ throw new core_1.MidwayCommonError('Middleware must have resolve method!');
56
+ }
57
+ }
58
+ else {
59
+ newMiddlewareArr.push(fn);
60
+ }
61
+ }
62
+ const composeFn = (req, res, next) => {
63
+ (function iter(i, max) {
64
+ if (i === max) {
65
+ return next();
66
+ }
67
+ newMiddlewareArr[i](req, res, iter.bind(this, i + 1, max));
68
+ })(0, newMiddlewareArr.length);
69
+ };
70
+ if (name) {
71
+ composeFn._name = name;
72
+ }
73
+ return composeFn;
74
+ }
75
+ };
76
+ MidwayExpressMiddlewareService = __decorate([
77
+ (0, decorator_1.Provide)(),
78
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
79
+ __metadata("design:paramtypes", [Object])
80
+ ], MidwayExpressMiddlewareService);
81
+ exports.MidwayExpressMiddlewareService = MidwayExpressMiddlewareService;
82
+ function wrapMiddleware(mw, options) {
83
+ // support options.enable
84
+ if (options.enable === false)
85
+ return null;
86
+ // support options.match and options.ignore
87
+ if (!options.match && !options.ignore)
88
+ return mw;
89
+ const match = (0, core_1.pathMatching)(options);
90
+ const fn = (req, res, next) => {
91
+ if (!match(req))
92
+ return next();
93
+ return mw(req, res, next);
94
+ };
95
+ fn._name = mw._name + 'middlewareWrapper';
96
+ return fn;
97
+ }
98
+ exports.wrapMiddleware = wrapMiddleware;
99
+ //# sourceMappingURL=middlewareService.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/express",
3
- "version": "3.0.0-alpha.6+6c8b724b",
3
+ "version": "3.0.0-beta.11",
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-alpha.6+6c8b724b",
27
- "@midwayjs/mock": "^3.0.0-alpha.6+6c8b724b",
26
+ "@midwayjs/decorator": "^3.0.0-beta.11",
27
+ "@midwayjs/logger": "^3.0.0-beta.11",
28
+ "@midwayjs/mock": "^3.0.0-beta.11",
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-alpha.6+6c8b724b",
33
- "@midwayjs/logger": "^3.0.0-alpha.6+6c8b724b",
34
+ "@midwayjs/core": "^3.0.0-beta.11",
35
+ "@midwayjs/express-session": "^3.0.0-beta.11",
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>",
@@ -38,5 +42,8 @@
38
42
  "type": "git",
39
43
  "url": "http://github.com/midwayjs/midway.git"
40
44
  },
41
- "gitHead": "6c8b724b08cf395287636b80387653f9540768e5"
45
+ "engines": {
46
+ "node": ">=12"
47
+ },
48
+ "gitHead": "a2b066fd500e815e799e7f421cd216f12e0e9f8e"
42
49
  }