@midwayjs/express 3.0.0-beta.10 → 3.0.0-beta.14

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,48 @@
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.14](https://github.com/midwayjs/midway/compare/v3.0.0-beta.13...v3.0.0-beta.14) (2022-01-04)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * cos config definition & 3.x doc update ([#1515](https://github.com/midwayjs/midway/issues/1515)) ([0ac7ac5](https://github.com/midwayjs/midway/commit/0ac7ac5805b7ab8873f8792fc1712a74e3223172))
12
+
13
+
14
+
15
+
16
+
17
+ # [3.0.0-beta.13](https://github.com/midwayjs/midway/compare/v3.0.0-beta.12...v3.0.0-beta.13) (2021-12-30)
18
+
19
+
20
+ ### Features
21
+
22
+ * 404 error ([#1465](https://github.com/midwayjs/midway/issues/1465)) ([e7e8a9d](https://github.com/midwayjs/midway/commit/e7e8a9dedfa7198ac05b161b41024c2871f93965))
23
+
24
+
25
+
26
+
27
+
28
+ # [3.0.0-beta.12](https://github.com/midwayjs/midway/compare/v3.0.0-beta.11...v3.0.0-beta.12) (2021-12-28)
29
+
30
+
31
+ ### Features
32
+
33
+ * custom error code & add @Files/@Fields ([#1438](https://github.com/midwayjs/midway/issues/1438)) ([b0032af](https://github.com/midwayjs/midway/commit/b0032afd2fa9ea0416fe69f4bd0c1a58bea5314e))
34
+ * support throw err status ([#1440](https://github.com/midwayjs/midway/issues/1440)) ([7b98110](https://github.com/midwayjs/midway/commit/7b98110d65c5287a8fcb3eb5356dea2d7a32cee9))
35
+
36
+
37
+
38
+
39
+
40
+ # [3.0.0-beta.11](https://github.com/midwayjs/midway/compare/v3.0.0-beta.10...v3.0.0-beta.11) (2021-12-21)
41
+
42
+ **Note:** Version bump only for package @midwayjs/express
43
+
44
+
45
+
46
+
47
+
6
48
  # [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
49
 
8
50
 
package/dist/framework.js CHANGED
@@ -12,13 +12,18 @@ const decorator_1 = require("@midwayjs/decorator");
12
12
  const express = require("express");
13
13
  const logger_1 = require("./logger");
14
14
  const middlewareService_1 = require("./middlewareService");
15
+ const util_1 = require("util");
16
+ const debug = (0, util_1.debuglog)('midway:debug');
15
17
  let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
16
18
  configure() {
17
19
  return this.configService.getConfiguration('express');
18
20
  }
19
21
  async applicationInitialize(options) {
20
22
  this.expressMiddlewareService = await this.applicationContext.getAsync(middlewareService_1.MidwayExpressMiddlewareService, [this.applicationContext]);
23
+ debug('[express]: create express app');
21
24
  this.app = express();
25
+ debug('[express]: use root middleware');
26
+ // use root middleware
22
27
  this.app.use((req, res, next) => {
23
28
  const ctx = req;
24
29
  this.app.createAnonymousContext(ctx);
@@ -27,25 +32,67 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
27
32
  ctx.requestContext.registerObject('res', res);
28
33
  next();
29
34
  });
35
+ this.defineApplicationProperties();
36
+ // hack use method
37
+ this.app.originUse = this.app.use;
38
+ this.app.use = this.app.useMiddleware;
30
39
  }
31
40
  async run() {
32
41
  var _a;
42
+ debug(`[express]: use middlewares = "${this.getMiddleware().getNames()}"`);
43
+ // restore use method
44
+ this.app.use = this.app.originUse;
33
45
  // use global middleware
34
46
  const globalMiddleware = await this.applyMiddleware();
47
+ debug('[express]: use and apply all framework and global middleware');
35
48
  this.app.use(globalMiddleware);
49
+ debug('[express]: use user router middleware');
36
50
  // load controller
37
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');
38
58
  // 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);
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;
42
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);
43
87
  next(error);
44
88
  }
45
89
  else {
46
90
  this.sendData(res, result);
47
91
  }
48
- }
92
+ })
93
+ .catch(err => {
94
+ next(err);
95
+ });
49
96
  });
50
97
  // https config
51
98
  if (this.configurationOptions.key && this.configurationOptions.cert) {
@@ -72,7 +119,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
72
119
  const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
73
120
  if (customPort) {
74
121
  new Promise(resolve => {
75
- const args = [this.configurationOptions.port];
122
+ const args = [customPort];
76
123
  if (this.configurationOptions.hostname) {
77
124
  args.push(this.configurationOptions.hostname);
78
125
  }
@@ -91,16 +138,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
91
138
  * wrap controller string to middleware function
92
139
  */
93
140
  generateController(routeInfo) {
94
- return async (req, res, next) => {
141
+ return (0, middlewareService_1.wrapAsyncHandler)(async (req, res, next) => {
95
142
  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;
103
- }
143
+ const result = await controller[routeInfo.method].call(controller, req, res, next);
104
144
  if (res.headersSent) {
105
145
  // return when response send
106
146
  return;
@@ -133,9 +173,10 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
133
173
  throw error;
134
174
  }
135
175
  this.sendData(res, returnValue);
136
- };
176
+ });
137
177
  }
138
178
  async loadMidwayController() {
179
+ var _a, _b;
139
180
  const collector = new core_1.WebRouterCollector('', {
140
181
  globalPrefix: this.configurationOptions.globalPrefix,
141
182
  });
@@ -147,6 +188,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
147
188
  this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
148
189
  // new router
149
190
  const newRouter = this.createRouter(routerInfo.routerOptions);
191
+ routerInfo.middleware = (_a = routerInfo.middleware) !== null && _a !== void 0 ? _a : [];
150
192
  // add router middleware
151
193
  if (routerInfo.middleware.length) {
152
194
  const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
@@ -157,6 +199,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
157
199
  for (const routeInfo of routes) {
158
200
  const routeMiddlewareList = [];
159
201
  // routeInfo middleware
202
+ routeInfo.middleware = (_b = routeInfo.middleware) !== null && _b !== void 0 ? _b : [];
160
203
  if (routeInfo.middleware.length) {
161
204
  const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
162
205
  routeMiddlewareList.push(routeMiddlewareFn);
@@ -1,11 +1,12 @@
1
1
  import { IMidwayContainer, CommonMiddleware, FunctionMiddleware } from '@midwayjs/core';
2
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
8
  compose(middleware: Array<CommonMiddleware<IMidwayExpressContext, Response, NextFunction> | string>, app: Application, name?: string): Promise<{
8
- (req: IMidwayExpressContext, res: Response, next: NextFunction): void;
9
+ (req: IMidwayExpressContext, res: Response, nextFunction: NextFunction): any;
9
10
  _name: string;
10
11
  }>;
11
12
  }
@@ -9,9 +9,22 @@ 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.wrapMiddleware = 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;
@@ -30,6 +43,8 @@ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
30
43
  const classMiddleware = await this.applicationContext.getAsync(fn);
31
44
  if (classMiddleware) {
32
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
@@ -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);
66
86
  }
67
- newMiddlewareArr[i](req, res, iter.bind(this, i + 1, max));
68
- })(0, newMiddlewareArr.length);
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);
95
+ }
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/express",
3
- "version": "3.0.0-beta.10",
3
+ "version": "3.0.0-beta.14",
4
4
  "description": "Midway Web Framework for Express",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -23,19 +23,19 @@
23
23
  ],
24
24
  "license": "MIT",
25
25
  "devDependencies": {
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",
30
- "@types/express": "^4.17.8",
31
- "fs-extra": "^8.0.1"
26
+ "@midwayjs/decorator": "^3.0.0-beta.14",
27
+ "@midwayjs/logger": "2.14.0",
28
+ "@midwayjs/mock": "^3.0.0-beta.14",
29
+ "@types/body-parser": "1.19.2",
30
+ "@types/express": "4.17.13",
31
+ "fs-extra": "10.0.0"
32
32
  },
33
33
  "dependencies": {
34
- "@midwayjs/core": "^3.0.0-beta.10",
35
- "@midwayjs/express-session": "^3.0.0-beta.10",
36
- "body-parser": "^1.19.0",
34
+ "@midwayjs/core": "^3.0.0-beta.14",
35
+ "@midwayjs/express-session": "^3.0.0-beta.14",
36
+ "body-parser": "1.19.1",
37
37
  "cookie-parser": "^1.4.6",
38
- "express": "^4.17.1"
38
+ "express": "4.17.2"
39
39
  },
40
40
  "author": "Harry Chen <czy88840616@gmail.com>",
41
41
  "repository": {
@@ -45,5 +45,5 @@
45
45
  "engines": {
46
46
  "node": ">=12"
47
47
  },
48
- "gitHead": "153870f2e2dd6b17673ec7591e49224a6bd51b36"
48
+ "gitHead": "95695ada36190cf376e93a1a8866b3fb6dde06bc"
49
49
  }