@midwayjs/express 3.0.0-beta.11 → 3.0.0-beta.12

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,18 @@
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.12](https://github.com/midwayjs/midway/compare/v3.0.0-beta.11...v3.0.0-beta.12) (2021-12-28)
7
+
8
+
9
+ ### Features
10
+
11
+ * custom error code & add @Files/@Fields ([#1438](https://github.com/midwayjs/midway/issues/1438)) ([b0032af](https://github.com/midwayjs/midway/commit/b0032afd2fa9ea0416fe69f4bd0c1a58bea5314e))
12
+ * support throw err status ([#1440](https://github.com/midwayjs/midway/issues/1440)) ([7b98110](https://github.com/midwayjs/midway/commit/7b98110d65c5287a8fcb3eb5356dea2d7a32cee9))
13
+
14
+
15
+
16
+
17
+
6
18
  # [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
19
 
8
20
  **Note:** Version bump only for package @midwayjs/express
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,62 @@ 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 global error handler middleware');
38
53
  // 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);
54
+ this.app.use((err, req, res, next) => {
55
+ this.filterManager
56
+ .runErrorFilter(err, req, res, next)
57
+ .then(data => {
58
+ var _a, _b;
59
+ const { result, error } = data;
42
60
  if (error) {
61
+ const status = (_b = (_a = error.status) !== null && _a !== void 0 ? _a : res.statusCode) !== null && _b !== void 0 ? _b : 500;
62
+ // 5xx
63
+ if (status >= 500) {
64
+ try {
65
+ req.logger.error(err);
66
+ }
67
+ catch (ex) {
68
+ this.logger.error(err);
69
+ this.logger.error(ex);
70
+ }
71
+ return;
72
+ }
73
+ // 4xx
74
+ try {
75
+ req.logger.warn(err);
76
+ }
77
+ catch (ex) {
78
+ this.logger.warn(err);
79
+ this.logger.error(ex);
80
+ }
81
+ res.status(status);
43
82
  next(error);
44
83
  }
45
84
  else {
46
85
  this.sendData(res, result);
47
86
  }
48
- }
87
+ })
88
+ .catch(err => {
89
+ next(err);
90
+ });
49
91
  });
50
92
  // https config
51
93
  if (this.configurationOptions.key && this.configurationOptions.cert) {
@@ -72,7 +114,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
72
114
  const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
73
115
  if (customPort) {
74
116
  new Promise(resolve => {
75
- const args = [this.configurationOptions.port];
117
+ const args = [customPort];
76
118
  if (this.configurationOptions.hostname) {
77
119
  args.push(this.configurationOptions.hostname);
78
120
  }
@@ -91,16 +133,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
91
133
  * wrap controller string to middleware function
92
134
  */
93
135
  generateController(routeInfo) {
94
- return async (req, res, next) => {
136
+ return (0, middlewareService_1.wrapAsyncHandler)(async (req, res, next) => {
95
137
  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
- }
138
+ const result = await controller[routeInfo.method].call(controller, req, res, next);
104
139
  if (res.headersSent) {
105
140
  // return when response send
106
141
  return;
@@ -133,9 +168,10 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
133
168
  throw error;
134
169
  }
135
170
  this.sendData(res, returnValue);
136
- };
171
+ });
137
172
  }
138
173
  async loadMidwayController() {
174
+ var _a, _b;
139
175
  const collector = new core_1.WebRouterCollector('', {
140
176
  globalPrefix: this.configurationOptions.globalPrefix,
141
177
  });
@@ -147,6 +183,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
147
183
  this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
148
184
  // new router
149
185
  const newRouter = this.createRouter(routerInfo.routerOptions);
186
+ routerInfo.middleware = (_a = routerInfo.middleware) !== null && _a !== void 0 ? _a : [];
150
187
  // add router middleware
151
188
  if (routerInfo.middleware.length) {
152
189
  const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
@@ -157,6 +194,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
157
194
  for (const routeInfo of routes) {
158
195
  const routeMiddlewareList = [];
159
196
  // routeInfo middleware
197
+ routeInfo.middleware = (_b = routeInfo.middleware) !== null && _b !== void 0 ? _b : [];
160
198
  if (routeInfo.middleware.length) {
161
199
  const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
162
200
  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.11",
3
+ "version": "3.0.0-beta.12",
4
4
  "description": "Midway Web Framework for Express",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -23,16 +23,16 @@
23
23
  ],
24
24
  "license": "MIT",
25
25
  "devDependencies": {
26
- "@midwayjs/decorator": "^3.0.0-beta.11",
27
- "@midwayjs/logger": "^3.0.0-beta.11",
28
- "@midwayjs/mock": "^3.0.0-beta.11",
26
+ "@midwayjs/decorator": "^3.0.0-beta.12",
27
+ "@midwayjs/logger": "^3.0.0-beta.12",
28
+ "@midwayjs/mock": "^3.0.0-beta.12",
29
29
  "@types/body-parser": "^1.19.2",
30
30
  "@types/express": "^4.17.8",
31
31
  "fs-extra": "^8.0.1"
32
32
  },
33
33
  "dependencies": {
34
- "@midwayjs/core": "^3.0.0-beta.11",
35
- "@midwayjs/express-session": "^3.0.0-beta.11",
34
+ "@midwayjs/core": "^3.0.0-beta.12",
35
+ "@midwayjs/express-session": "^3.0.0-beta.12",
36
36
  "body-parser": "^1.19.0",
37
37
  "cookie-parser": "^1.4.6",
38
38
  "express": "^4.17.1"
@@ -45,5 +45,5 @@
45
45
  "engines": {
46
46
  "node": ">=12"
47
47
  },
48
- "gitHead": "a2b066fd500e815e799e7f421cd216f12e0e9f8e"
48
+ "gitHead": "1c46e53eb934248007eeb7fe3920f5ac24e272c6"
49
49
  }