@midwayjs/express 3.0.0-alpha.43 → 3.0.0-beta.10

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,108 @@
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.10](https://github.com/midwayjs/midway/compare/v3.0.0-beta.9...v3.0.0-beta.10) (2021-12-20)
7
+
8
+
9
+ ### Features
10
+
11
+ * 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))
12
+ * implement i18n for validate ([#1426](https://github.com/midwayjs/midway/issues/1426)) ([4c7ed2f](https://github.com/midwayjs/midway/commit/4c7ed2ff2e7ccf10f88f62abad230f92f5e76b97))
13
+
14
+
15
+
16
+
17
+
18
+ # [3.0.0-beta.9](https://github.com/midwayjs/midway/compare/v3.0.0-beta.8...v3.0.0-beta.9) (2021-12-09)
19
+
20
+ **Note:** Version bump only for package @midwayjs/express
21
+
22
+
23
+
24
+
25
+
26
+ # [3.0.0-beta.8](https://github.com/midwayjs/midway/compare/v3.0.0-beta.7...v3.0.0-beta.8) (2021-12-08)
27
+
28
+
29
+ ### Bug Fixes
30
+
31
+ * 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))
32
+ * typeorm EntityView missing connectionName ([#1403](https://github.com/midwayjs/midway/issues/1403)) ([30b2b37](https://github.com/midwayjs/midway/commit/30b2b3711db485cb85d825d56aeabf53b1374cae))
33
+
34
+
35
+
36
+
37
+
38
+ # [3.0.0-beta.7](https://github.com/midwayjs/midway/compare/v3.0.0-beta.6...v3.0.0-beta.7) (2021-12-03)
39
+
40
+ **Note:** Version bump only for package @midwayjs/express
41
+
42
+
43
+
44
+
45
+
46
+ # [3.0.0-beta.6](https://github.com/midwayjs/midway/compare/v3.0.0-beta.5...v3.0.0-beta.6) (2021-11-26)
47
+
48
+
49
+ ### Bug Fixes
50
+
51
+ * class transformer method missing ([#1387](https://github.com/midwayjs/midway/issues/1387)) ([074e839](https://github.com/midwayjs/midway/commit/074e8393598dc95e2742f735df75a2191c5fe25d))
52
+
53
+
54
+
55
+
56
+
57
+ # [3.0.0-beta.5](https://github.com/midwayjs/midway/compare/v3.0.0-beta.4...v3.0.0-beta.5) (2021-11-25)
58
+
59
+ **Note:** Version bump only for package @midwayjs/express
60
+
61
+
62
+
63
+
64
+
65
+ # [3.0.0-beta.4](https://github.com/midwayjs/midway/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-11-24)
66
+
67
+
68
+ ### Features
69
+
70
+ * add i18n ([#1375](https://github.com/midwayjs/midway/issues/1375)) ([bffefe0](https://github.com/midwayjs/midway/commit/bffefe07afe45777d49b5a76b9ab17fc2b9d9a55))
71
+ * auto transform args to type ([#1372](https://github.com/midwayjs/midway/issues/1372)) ([bb3f7d2](https://github.com/midwayjs/midway/commit/bb3f7d2028a034e1926d9df554849332354c3762))
72
+ * support global prefix url ([#1371](https://github.com/midwayjs/midway/issues/1371)) ([cc5fe44](https://github.com/midwayjs/midway/commit/cc5fe44e1d221590562dc71e1f33ae96093e0da7))
73
+
74
+
75
+
76
+
77
+
78
+ # [3.0.0-beta.3](https://github.com/midwayjs/midway/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-11-18)
79
+
80
+
81
+ ### Features
82
+
83
+ * add component and framework config definition ([#1367](https://github.com/midwayjs/midway/issues/1367)) ([b2fe615](https://github.com/midwayjs/midway/commit/b2fe6157f99659471ff1333eca0b86bb889f61a3))
84
+
85
+
86
+
87
+
88
+
89
+ # [3.0.0-beta.2](https://github.com/midwayjs/midway/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-11-16)
90
+
91
+ **Note:** Version bump only for package @midwayjs/express
92
+
93
+
94
+
95
+
96
+
97
+ # [3.0.0-beta.1](https://github.com/midwayjs/midway/compare/v2.12.4...v3.0.0-beta.1) (2021-11-14)
98
+
99
+
100
+ ### Features
101
+
102
+ * add http2 support ([#1242](https://github.com/midwayjs/midway/issues/1242)) ([6cda27e](https://github.com/midwayjs/midway/commit/6cda27e9e22689e46ace543326b43ae21b134911))
103
+
104
+
105
+
106
+
107
+
6
108
  ## [2.12.3](https://github.com/midwayjs/midway/compare/v2.12.2...v2.12.3) (2021-08-09)
7
109
 
8
110
  **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,34 +1,52 @@
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);
@@ -51,12 +69,8 @@ class MidwayExpressFramework extends core_1.BaseFramework {
51
69
  }
52
70
  // register httpServer to applicationContext
53
71
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
54
- }
55
- async afterContainerReady(options) {
56
- await this.loadMidwayController();
57
- }
58
- async run() {
59
- if (this.configurationOptions.port) {
72
+ const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
73
+ if (customPort) {
60
74
  new Promise(resolve => {
61
75
  const args = [this.configurationOptions.port];
62
76
  if (this.configurationOptions.hostname) {
@@ -66,6 +80,7 @@ class MidwayExpressFramework extends core_1.BaseFramework {
66
80
  resolve();
67
81
  });
68
82
  this.server.listen(...args);
83
+ process.env.MIDWAY_HTTP_PORT = String(customPort);
69
84
  });
70
85
  }
71
86
  }
@@ -74,22 +89,18 @@ class MidwayExpressFramework extends core_1.BaseFramework {
74
89
  }
75
90
  /**
76
91
  * wrap controller string to middleware function
77
- * @param controllerMapping like FooController.index
78
- * @param routeArgsInfo
79
- * @param routerResponseData
80
92
  */
81
- generateController(controllerMapping, routeArgsInfo, routerResponseData) {
82
- const [controllerId, methodName] = controllerMapping.split('.');
93
+ generateController(routeInfo) {
83
94
  return async (req, res, next) => {
84
- const args = [req, res, next];
85
- if (Array.isArray(routeArgsInfo)) {
86
- await Promise.all(routeArgsInfo.map(async ({ index, type, propertyData }) => {
87
- args[index] = await (0, core_1.extractExpressLikeValue)(type, propertyData)(req, res, next);
88
- }));
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;
89
103
  }
90
- const controller = await req.requestContext.getAsync(controllerId);
91
- // eslint-disable-next-line prefer-spread
92
- const result = await controller[methodName].apply(controller, args);
93
104
  if (res.headersSent) {
94
105
  // return when response send
95
106
  return;
@@ -98,8 +109,9 @@ class MidwayExpressFramework extends core_1.BaseFramework {
98
109
  res.status(204);
99
110
  }
100
111
  // implement response decorator
101
- if (Array.isArray(routerResponseData) && routerResponseData.length) {
102
- for (const routerRes of routerResponseData) {
112
+ if (Array.isArray(routeInfo.responseMetadata) &&
113
+ routeInfo.responseMetadata.length) {
114
+ for (const routerRes of routeInfo.responseMetadata) {
103
115
  switch (routerRes.type) {
104
116
  case decorator_1.WEB_RESPONSE_HTTP_CODE:
105
117
  res.status(routerRes.code);
@@ -116,68 +128,58 @@ class MidwayExpressFramework extends core_1.BaseFramework {
116
128
  }
117
129
  }
118
130
  }
119
- 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);
120
136
  };
121
137
  }
122
138
  async loadMidwayController() {
123
- const collector = new core_1.WebRouterCollector();
139
+ const collector = new core_1.WebRouterCollector('', {
140
+ globalPrefix: this.configurationOptions.globalPrefix,
141
+ });
124
142
  const routerTable = await collector.getRouterTable();
125
143
  const routerList = await collector.getRoutePriorityList();
126
144
  for (const routerInfo of routerList) {
127
145
  // bind controller first
128
146
  this.getApplicationContext().bindClass(routerInfo.routerModule);
129
- const providerId = routerInfo.controllerId;
130
- // controller id check
131
- if (this.controllerIds.indexOf(providerId) > -1) {
132
- throw new Error(`Controller identifier [${providerId}] already exists!`);
133
- }
134
- this.controllerIds.push(providerId);
135
- this.logger.debug(`Load Controller "${providerId}", prefix=${routerInfo.prefix}`);
147
+ this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
136
148
  // new router
137
149
  const newRouter = this.createRouter(routerInfo.routerOptions);
138
150
  // add router middleware
139
- await this.handlerWebMiddleware(routerInfo.middleware, (middlewareImpl) => {
140
- newRouter.use(middlewareImpl);
141
- });
151
+ if (routerInfo.middleware.length) {
152
+ const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
153
+ newRouter.use(routerMiddlewareFn);
154
+ }
142
155
  // add route
143
156
  const routes = routerTable.get(routerInfo.prefix);
144
157
  for (const routeInfo of routes) {
145
- // router middleware
146
- await this.handlerWebMiddleware(routeInfo.middleware, (middlewareImpl) => {
147
- newRouter.use(middlewareImpl);
148
- });
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
+ }
149
164
  this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
150
165
  // apply controller from request context
151
- 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));
152
167
  }
153
168
  this.app.use(routerInfo.prefix, newRouter);
154
169
  }
155
170
  }
156
- async generateMiddleware(middlewareId) {
157
- const mwIns = await this.getApplicationContext().getAsync(middlewareId);
158
- return mwIns.resolve();
159
- }
160
171
  /**
161
- * @param controllerOption
172
+ * @param routerOptions
162
173
  */
163
174
  createRouter(routerOptions) {
164
175
  return express.Router({ caseSensitive: routerOptions.sensitive });
165
176
  }
166
- async handlerWebMiddleware(middlewares, handlerCallback) {
167
- if (middlewares && middlewares.length) {
168
- for (const middleware of middlewares) {
169
- if (typeof middleware === 'function') {
170
- // web function middleware
171
- handlerCallback(middleware);
172
- }
173
- else {
174
- const middlewareImpl = await this.getApplicationContext().getAsync(middleware);
175
- if (middlewareImpl && typeof middlewareImpl.resolve === 'function') {
176
- handlerCallback(middlewareImpl.resolve());
177
- }
178
- }
179
- }
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);
180
181
  }
182
+ return this.composeMiddleware;
181
183
  }
182
184
  async beforeStop() {
183
185
  this.server.close();
@@ -191,6 +193,17 @@ class MidwayExpressFramework extends core_1.BaseFramework {
191
193
  getDefaultContextLoggerClass() {
192
194
  return logger_1.MidwayExpressContextLogger;
193
195
  }
194
- }
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);
195
208
  exports.MidwayExpressFramework = MidwayExpressFramework;
196
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
  */
@@ -47,13 +48,33 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
47
48
  * http2 support
48
49
  */
49
50
  http2?: boolean;
50
- }
51
- export declare type MiddlewareParamArray = RequestHandler[];
52
- export declare type Middleware = RequestHandler;
53
- export interface IWebMiddleware {
54
- resolve(): Middleware;
51
+ /**
52
+ * http global prefix
53
+ */
54
+ globalPrefix?: string;
55
55
  }
56
56
  export declare type Application = IMidwayExpressApplication;
57
+ export declare type NextFunction = ExpressNextFunction;
57
58
  export interface Context extends IMidwayExpressContext {
58
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
+ }
59
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.43+8b8075f0",
3
+ "version": "3.0.0-beta.10",
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.43+8b8075f0",
27
- "@midwayjs/mock": "^3.0.0-alpha.43+8b8075f0",
26
+ "@midwayjs/decorator": "^3.0.0-beta.10",
27
+ "@midwayjs/logger": "^3.0.0-beta.10",
28
+ "@midwayjs/mock": "^3.0.0-beta.10",
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.43+8b8075f0",
33
- "@midwayjs/logger": "^3.0.0-alpha.43+8b8075f0",
34
+ "@midwayjs/core": "^3.0.0-beta.10",
35
+ "@midwayjs/express-session": "^3.0.0-beta.10",
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>",
@@ -39,7 +43,7 @@
39
43
  "url": "http://github.com/midwayjs/midway.git"
40
44
  },
41
45
  "engines": {
42
- "node": ">=10.10.0"
46
+ "node": ">=12"
43
47
  },
44
- "gitHead": "8b8075f0d40c5de19bb9026f0950e738ca512c7e"
48
+ "gitHead": "153870f2e2dd6b17673ec7591e49224a6bd51b36"
45
49
  }