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

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,57 @@
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.15](https://github.com/midwayjs/midway/compare/v3.0.0-beta.14...v3.0.0-beta.15) (2022-01-07)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * serverless app run ([#1523](https://github.com/midwayjs/midway/issues/1523)) ([5a25eb7](https://github.com/midwayjs/midway/commit/5a25eb7ebb17bf9b0e2ba4feee5bc1649f70d56f))
12
+
13
+
14
+ ### Features
15
+
16
+ * add info middleware ([#1530](https://github.com/midwayjs/midway/issues/1530)) ([7077f1d](https://github.com/midwayjs/midway/commit/7077f1d84355633a1c2fced35bfcc2152f42a7ac))
17
+ * add secret filter ([#1531](https://github.com/midwayjs/midway/issues/1531)) ([ce77e48](https://github.com/midwayjs/midway/commit/ce77e4804aaffc18a0a091d3726e36d7ec1514b2))
18
+
19
+
20
+
21
+
22
+
23
+ # [3.0.0-beta.14](https://github.com/midwayjs/midway/compare/v3.0.0-beta.13...v3.0.0-beta.14) (2022-01-04)
24
+
25
+
26
+ ### Bug Fixes
27
+
28
+ * cos config definition & 3.x doc update ([#1515](https://github.com/midwayjs/midway/issues/1515)) ([0ac7ac5](https://github.com/midwayjs/midway/commit/0ac7ac5805b7ab8873f8792fc1712a74e3223172))
29
+
30
+
31
+
32
+
33
+
34
+ # [3.0.0-beta.13](https://github.com/midwayjs/midway/compare/v3.0.0-beta.12...v3.0.0-beta.13) (2021-12-30)
35
+
36
+
37
+ ### Features
38
+
39
+ * 404 error ([#1465](https://github.com/midwayjs/midway/issues/1465)) ([e7e8a9d](https://github.com/midwayjs/midway/commit/e7e8a9dedfa7198ac05b161b41024c2871f93965))
40
+
41
+
42
+
43
+
44
+
45
+ # [3.0.0-beta.12](https://github.com/midwayjs/midway/compare/v3.0.0-beta.11...v3.0.0-beta.12) (2021-12-28)
46
+
47
+
48
+ ### Features
49
+
50
+ * custom error code & add @Files/@Fields ([#1438](https://github.com/midwayjs/midway/issues/1438)) ([b0032af](https://github.com/midwayjs/midway/commit/b0032afd2fa9ea0416fe69f4bd0c1a58bea5314e))
51
+ * support throw err status ([#1440](https://github.com/midwayjs/midway/issues/1440)) ([7b98110](https://github.com/midwayjs/midway/commit/7b98110d65c5287a8fcb3eb5356dea2d7a32cee9))
52
+
53
+
54
+
55
+
56
+
6
57
  # [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
58
 
8
59
  **Note:** Version bump only for package @midwayjs/express
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # midway-web
1
+ # midway for express
2
2
 
3
- [![Package Quality](http://npm.packagequality.com/shield/midway-web.svg)](http://packagequality.com/#?package=midway-web)
3
+ [![Package Quality](http://npm.packagequality.com/shield/@midwayjs/express.svg)](http://packagequality.com/#?package=@midwayjs/express)
4
4
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/midwayjs/midway/pulls)
5
5
 
6
6
  this is a sub package for midway.
@@ -16,7 +16,10 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
16
16
  * wrap controller string to middleware function
17
17
  */
18
18
  protected generateController(routeInfo: RouterInfo): IRouterHandler<any>;
19
- loadMidwayController(): Promise<void>;
19
+ loadMidwayController(): Promise<Array<{
20
+ prefix: string;
21
+ middleware: any;
22
+ }>>;
20
23
  /**
21
24
  * @param routerOptions
22
25
  */
@@ -28,6 +31,5 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
28
31
  getServer(): Server;
29
32
  getFrameworkName(): string;
30
33
  getDefaultContextLoggerClass(): typeof MidwayExpressContextLogger;
31
- protected sendData(res: any, data: any): void;
32
34
  }
33
35
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -12,13 +12,19 @@ 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 util_2 = require("./util");
17
+ const debug = (0, util_1.debuglog)('midway:debug');
15
18
  let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
16
19
  configure() {
17
20
  return this.configService.getConfiguration('express');
18
21
  }
19
22
  async applicationInitialize(options) {
20
23
  this.expressMiddlewareService = await this.applicationContext.getAsync(middlewareService_1.MidwayExpressMiddlewareService, [this.applicationContext]);
24
+ debug('[express]: create express app');
21
25
  this.app = express();
26
+ debug('[express]: use root middleware');
27
+ // use root middleware
22
28
  this.app.use((req, res, next) => {
23
29
  const ctx = req;
24
30
  this.app.createAnonymousContext(ctx);
@@ -27,25 +33,71 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
27
33
  ctx.requestContext.registerObject('res', res);
28
34
  next();
29
35
  });
36
+ this.defineApplicationProperties();
37
+ // hack use method
38
+ this.app.originUse = this.app.use;
39
+ this.app.use = this.app.useMiddleware;
30
40
  }
31
41
  async run() {
32
42
  var _a;
43
+ debug(`[express]: use middlewares = "${this.getMiddleware().getNames()}"`);
44
+ // restore use method
45
+ this.app.use = this.app.originUse;
46
+ debug('[express]: use user router middleware');
47
+ // load controller,must apply router filter here
48
+ const routerMiddlewares = await this.loadMidwayController();
33
49
  // use global middleware
34
50
  const globalMiddleware = await this.applyMiddleware();
51
+ debug('[express]: use and apply all framework and global middleware');
35
52
  this.app.use(globalMiddleware);
36
- // load controller
37
- await this.loadMidwayController();
53
+ // load router after global middleware
54
+ for (const info of routerMiddlewares) {
55
+ this.app.use(info.prefix, info.middleware);
56
+ }
57
+ debug('[express]: use 404 not found middleware');
58
+ // eslint-disable-next-line
59
+ this.app.use(function notFound(req, res, next) {
60
+ next(new core_1.httpError.NotFoundError());
61
+ });
62
+ debug('[express]: use global error handler middleware');
38
63
  // 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);
64
+ this.app.use((err, req, res, next) => {
65
+ this.filterManager
66
+ .runErrorFilter(err, req, res, next)
67
+ .then(data => {
68
+ var _a, _b;
69
+ const { result, error } = data;
42
70
  if (error) {
71
+ const status = (_b = (_a = error.status) !== null && _a !== void 0 ? _a : res.statusCode) !== null && _b !== void 0 ? _b : 500;
72
+ // 5xx
73
+ if (status >= 500) {
74
+ try {
75
+ req.logger.error(err);
76
+ }
77
+ catch (ex) {
78
+ this.logger.error(err);
79
+ this.logger.error(ex);
80
+ }
81
+ return;
82
+ }
83
+ // 4xx
84
+ try {
85
+ req.logger.warn(err);
86
+ }
87
+ catch (ex) {
88
+ this.logger.warn(err);
89
+ this.logger.error(ex);
90
+ }
91
+ res.status(status);
43
92
  next(error);
44
93
  }
45
94
  else {
46
- this.sendData(res, result);
95
+ (0, util_2.sendData)(res, result);
47
96
  }
48
- }
97
+ })
98
+ .catch(err => {
99
+ next(err);
100
+ });
49
101
  });
50
102
  // https config
51
103
  if (this.configurationOptions.key && this.configurationOptions.cert) {
@@ -72,7 +124,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
72
124
  const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
73
125
  if (customPort) {
74
126
  new Promise(resolve => {
75
- const args = [this.configurationOptions.port];
127
+ const args = [customPort];
76
128
  if (this.configurationOptions.hostname) {
77
129
  args.push(this.configurationOptions.hostname);
78
130
  }
@@ -91,16 +143,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
91
143
  * wrap controller string to middleware function
92
144
  */
93
145
  generateController(routeInfo) {
94
- return async (req, res, next) => {
146
+ return (0, middlewareService_1.wrapAsyncHandler)(async (req, res, next) => {
95
147
  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
- }
148
+ const result = await controller[routeInfo.method].call(controller, req, res, next);
104
149
  if (res.headersSent) {
105
150
  // return when response send
106
151
  return;
@@ -132,21 +177,24 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
132
177
  if (error) {
133
178
  throw error;
134
179
  }
135
- this.sendData(res, returnValue);
136
- };
180
+ (0, util_2.sendData)(res, returnValue);
181
+ });
137
182
  }
138
183
  async loadMidwayController() {
184
+ var _a, _b;
139
185
  const collector = new core_1.WebRouterCollector('', {
140
186
  globalPrefix: this.configurationOptions.globalPrefix,
141
187
  });
142
188
  const routerTable = await collector.getRouterTable();
143
189
  const routerList = await collector.getRoutePriorityList();
190
+ const routerMiddlewares = [];
144
191
  for (const routerInfo of routerList) {
145
192
  // bind controller first
146
193
  this.getApplicationContext().bindClass(routerInfo.routerModule);
147
194
  this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
148
195
  // new router
149
196
  const newRouter = this.createRouter(routerInfo.routerOptions);
197
+ routerInfo.middleware = (_a = routerInfo.middleware) !== null && _a !== void 0 ? _a : [];
150
198
  // add router middleware
151
199
  if (routerInfo.middleware.length) {
152
200
  const routerMiddlewareFn = await this.expressMiddlewareService.compose(routerInfo.middleware, this.app);
@@ -157,6 +205,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
157
205
  for (const routeInfo of routes) {
158
206
  const routeMiddlewareList = [];
159
207
  // routeInfo middleware
208
+ routeInfo.middleware = (_b = routeInfo.middleware) !== null && _b !== void 0 ? _b : [];
160
209
  if (routeInfo.middleware.length) {
161
210
  const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
162
211
  routeMiddlewareList.push(routeMiddlewareFn);
@@ -165,8 +214,12 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
165
214
  // apply controller from request context
166
215
  newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
167
216
  }
168
- this.app.use(routerInfo.prefix, newRouter);
217
+ routerMiddlewares.push({
218
+ prefix: routerInfo.prefix,
219
+ middleware: newRouter,
220
+ });
169
221
  }
222
+ return routerMiddlewares;
170
223
  }
171
224
  /**
172
225
  * @param routerOptions
@@ -193,14 +246,6 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
193
246
  getDefaultContextLoggerClass() {
194
247
  return logger_1.MidwayExpressContextLogger;
195
248
  }
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
249
  };
205
250
  MidwayExpressFramework = __decorate([
206
251
  (0, decorator_1.Framework)()
@@ -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,23 @@ 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
+ const util_1 = require("./util");
16
+ function wrapAsyncHandler(fn) {
17
+ if ((0, decorator_1.isAsyncFunction)(fn)) {
18
+ return (req, res, next) => {
19
+ return fn(req, res, next).catch(err => {
20
+ next(err);
21
+ });
22
+ };
23
+ }
24
+ else {
25
+ return fn;
26
+ }
27
+ }
28
+ exports.wrapAsyncHandler = wrapAsyncHandler;
15
29
  let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
16
30
  constructor(applicationContext) {
17
31
  this.applicationContext = applicationContext;
@@ -30,6 +44,8 @@ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
30
44
  const classMiddleware = await this.applicationContext.getAsync(fn);
31
45
  if (classMiddleware) {
32
46
  fn = classMiddleware.resolve(app);
47
+ // wrap async middleware
48
+ fn = wrapAsyncHandler(fn);
33
49
  if (!classMiddleware.match && !classMiddleware.ignore) {
34
50
  fn._name = classMiddleware.constructor.name;
35
51
  // just got fn
@@ -56,16 +72,40 @@ let MidwayExpressMiddlewareService = class MidwayExpressMiddlewareService {
56
72
  }
57
73
  }
58
74
  else {
75
+ // wrap async middleware
76
+ fn = wrapAsyncHandler(fn);
59
77
  newMiddlewareArr.push(fn);
60
78
  }
61
79
  }
62
- const composeFn = (req, res, next) => {
63
- (function iter(i, max) {
64
- if (i === max) {
65
- return next();
80
+ const composeFn = (req, res, nextFunction) => {
81
+ let index = -1;
82
+ function dispatch(pos, err) {
83
+ const handler = newMiddlewareArr[pos];
84
+ index = pos;
85
+ if (err || index === newMiddlewareArr.length) {
86
+ return nextFunction(err);
66
87
  }
67
- newMiddlewareArr[i](req, res, iter.bind(this, i + 1, max));
68
- })(0, newMiddlewareArr.length);
88
+ function next(err) {
89
+ if (pos < index) {
90
+ throw new TypeError('`next()` called multiple times');
91
+ }
92
+ return dispatch(pos + 1, err);
93
+ }
94
+ try {
95
+ Promise.resolve(handler(req, res, next)).then(result => {
96
+ if (result) {
97
+ (0, util_1.sendData)(res, result);
98
+ }
99
+ });
100
+ }
101
+ catch (err) {
102
+ // Avoid future errors that could diverge stack execution.
103
+ if (index > pos)
104
+ throw err;
105
+ return next(err);
106
+ }
107
+ }
108
+ return dispatch(0);
69
109
  };
70
110
  if (name) {
71
111
  composeFn._name = name;
package/dist/util.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function sendData(res: any, data: any): void;
2
+ //# sourceMappingURL=util.d.ts.map
package/dist/util.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendData = void 0;
4
+ function sendData(res, data) {
5
+ if (typeof data === 'number') {
6
+ res.status(res.statusCode).send('' + data);
7
+ }
8
+ else {
9
+ res.status(res.statusCode).send(data);
10
+ }
11
+ }
12
+ exports.sendData = sendData;
13
+ //# sourceMappingURL=util.js.map
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.15",
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.11",
27
- "@midwayjs/logger": "^3.0.0-beta.11",
28
- "@midwayjs/mock": "^3.0.0-beta.11",
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.15",
27
+ "@midwayjs/logger": "2.14.0",
28
+ "@midwayjs/mock": "^3.0.0-beta.15",
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.11",
35
- "@midwayjs/express-session": "^3.0.0-beta.11",
36
- "body-parser": "^1.19.0",
34
+ "@midwayjs/core": "^3.0.0-beta.15",
35
+ "@midwayjs/express-session": "^3.0.0-beta.15",
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": "a2b066fd500e815e799e7f421cd216f12e0e9f8e"
48
+ "gitHead": "6b9778557289d9e8b562c7ce6127736db1248973"
49
49
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2013 - Now midwayjs
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.