@midwayjs/express 3.0.0-alpha.9 → 3.0.0-beta.4

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,49 @@
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.4](https://github.com/midwayjs/midway/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-11-24)
7
+
8
+
9
+ ### Features
10
+
11
+ * add i18n ([#1375](https://github.com/midwayjs/midway/issues/1375)) ([bffefe0](https://github.com/midwayjs/midway/commit/bffefe07afe45777d49b5a76b9ab17fc2b9d9a55))
12
+ * auto transform args to type ([#1372](https://github.com/midwayjs/midway/issues/1372)) ([bb3f7d2](https://github.com/midwayjs/midway/commit/bb3f7d2028a034e1926d9df554849332354c3762))
13
+ * support global prefix url ([#1371](https://github.com/midwayjs/midway/issues/1371)) ([cc5fe44](https://github.com/midwayjs/midway/commit/cc5fe44e1d221590562dc71e1f33ae96093e0da7))
14
+
15
+
16
+
17
+
18
+
19
+ # [3.0.0-beta.3](https://github.com/midwayjs/midway/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-11-18)
20
+
21
+
22
+ ### Features
23
+
24
+ * add component and framework config definition ([#1367](https://github.com/midwayjs/midway/issues/1367)) ([b2fe615](https://github.com/midwayjs/midway/commit/b2fe6157f99659471ff1333eca0b86bb889f61a3))
25
+
26
+
27
+
28
+
29
+
30
+ # [3.0.0-beta.2](https://github.com/midwayjs/midway/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-11-16)
31
+
32
+ **Note:** Version bump only for package @midwayjs/express
33
+
34
+
35
+
36
+
37
+
38
+ # [3.0.0-beta.1](https://github.com/midwayjs/midway/compare/v2.12.4...v3.0.0-beta.1) (2021-11-14)
39
+
40
+
41
+ ### Features
42
+
43
+ * add http2 support ([#1242](https://github.com/midwayjs/midway/issues/1242)) ([6cda27e](https://github.com/midwayjs/midway/commit/6cda27e9e22689e46ace543326b43ae21b134911))
44
+
45
+
46
+
47
+
48
+
6
49
  ## [2.12.3](https://github.com/midwayjs/midway/compare/v2.12.2...v2.12.3) (2021-08-09)
7
50
 
8
51
  **Note:** Version bump only for package @midwayjs/express
@@ -0,0 +1,7 @@
1
+ import { MidwayDecoratorService } from '@midwayjs/core';
2
+ export declare class ExpressConfiguration {
3
+ decoratorService: MidwayDecoratorService;
4
+ init(): void;
5
+ onReady(): Promise<void>;
6
+ }
7
+ //# sourceMappingURL=configuration.d.ts.map
@@ -0,0 +1,39 @@
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
+ let ExpressConfiguration = class ExpressConfiguration {
16
+ init() {
17
+ this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
18
+ return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData, options.originParamType)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
19
+ });
20
+ }
21
+ async onReady() { }
22
+ };
23
+ __decorate([
24
+ (0, decorator_1.Inject)(),
25
+ __metadata("design:type", core_1.MidwayDecoratorService)
26
+ ], ExpressConfiguration.prototype, "decoratorService", void 0);
27
+ __decorate([
28
+ (0, decorator_1.Init)(),
29
+ __metadata("design:type", Function),
30
+ __metadata("design:paramtypes", []),
31
+ __metadata("design:returntype", void 0)
32
+ ], ExpressConfiguration.prototype, "init", null);
33
+ ExpressConfiguration = __decorate([
34
+ (0, decorator_1.Configuration)({
35
+ namespace: 'express',
36
+ })
37
+ ], ExpressConfiguration);
38
+ exports.ExpressConfiguration = ExpressConfiguration;
39
+ //# sourceMappingURL=configuration.js.map
@@ -1,39 +1,30 @@
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
26
  private handlerWebMiddleware;
27
+ getMiddleware<Response, NextFunction>(): Promise<MiddlewareRespond<IMidwayExpressContext, Response, NextFunction>>;
37
28
  beforeStop(): Promise<void>;
38
29
  getServer(): Server;
39
30
  getFrameworkName(): string;
package/dist/framework.js CHANGED
@@ -1,51 +1,75 @@
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
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.MidwayExpressFramework = void 0;
4
13
  const core_1 = require("@midwayjs/core");
5
14
  const decorator_1 = require("@midwayjs/decorator");
6
15
  const express = require("express");
7
16
  const logger_1 = require("./logger");
8
- class MidwayExpressFramework extends core_1.BaseFramework {
9
- constructor() {
10
- super(...arguments);
11
- this.controllerIds = [];
12
- this.prioritySortRouters = [];
17
+ const middlewareService_1 = require("./middlewareService");
18
+ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
19
+ configure() {
20
+ return this.configService.getConfiguration('express');
13
21
  }
14
22
  async applicationInitialize(options) {
15
23
  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
24
  this.app.use((req, res, next) => {
25
- const ctx = { req, res };
25
+ const ctx = req;
26
26
  this.app.createAnonymousContext(ctx);
27
27
  req.requestContext = ctx.requestContext;
28
28
  ctx.requestContext.registerObject('req', req);
29
29
  ctx.requestContext.registerObject('res', res);
30
30
  next();
31
31
  });
32
+ }
33
+ async run() {
34
+ // use global middleware
35
+ const globalMiddleware = await this.getMiddleware();
36
+ this.app.use(globalMiddleware);
37
+ // load controller
38
+ await this.loadMidwayController();
39
+ // use global error handler
40
+ this.app.use(async (err, req, res, next) => {
41
+ if (err) {
42
+ const { result, error } = await this.filterManager.runErrorFilter(err, req, res, next);
43
+ if (error) {
44
+ next(error);
45
+ }
46
+ else {
47
+ res.send(result);
48
+ }
49
+ }
50
+ });
32
51
  // https config
33
52
  if (this.configurationOptions.key && this.configurationOptions.cert) {
34
53
  this.configurationOptions.key = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.key);
35
54
  this.configurationOptions.cert = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.cert);
36
55
  this.configurationOptions.ca = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.ca);
37
- this.server = require('https').createServer(this.configurationOptions, this.app);
56
+ if (this.configurationOptions.http2) {
57
+ this.server = require('http2').createSecureServer(this.configurationOptions, this.app);
58
+ }
59
+ else {
60
+ this.server = require('https').createServer(this.configurationOptions, this.app);
61
+ }
38
62
  }
39
63
  else {
40
- this.server = require('http').createServer(this.app);
64
+ if (this.configurationOptions.http2) {
65
+ this.server = require('http2').createServer(this.app);
66
+ }
67
+ else {
68
+ this.server = require('http').createServer(this.app);
69
+ }
41
70
  }
42
71
  // register httpServer to applicationContext
43
72
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
44
- }
45
- async afterContainerReady(options) {
46
- await this.loadMidwayController();
47
- }
48
- async run() {
49
73
  if (this.configurationOptions.port) {
50
74
  new Promise(resolve => {
51
75
  const args = [this.configurationOptions.port];
@@ -64,22 +88,11 @@ class MidwayExpressFramework extends core_1.BaseFramework {
64
88
  }
65
89
  /**
66
90
  * wrap controller string to middleware function
67
- * @param controllerMapping like FooController.index
68
- * @param routeArgsInfo
69
- * @param routerResponseData
70
91
  */
71
- generateController(controllerMapping, routeArgsInfo, routerResponseData) {
72
- const [controllerId, methodName] = controllerMapping.split('.');
92
+ generateController(routeInfo) {
73
93
  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
- }));
79
- }
80
- const controller = await req.requestContext.getAsync(controllerId);
81
- // eslint-disable-next-line prefer-spread
82
- const result = await controller[methodName].apply(controller, args);
94
+ const controller = await req.requestContext.getAsync(routeInfo.id);
95
+ const result = await controller[routeInfo.method].call(controller, req, res, next);
83
96
  if (res.headersSent) {
84
97
  // return when response send
85
98
  return;
@@ -88,8 +101,9 @@ class MidwayExpressFramework extends core_1.BaseFramework {
88
101
  res.status(204);
89
102
  }
90
103
  // implement response decorator
91
- if (Array.isArray(routerResponseData) && routerResponseData.length) {
92
- for (const routerRes of routerResponseData) {
104
+ if (Array.isArray(routeInfo.responseMetadata) &&
105
+ routeInfo.responseMetadata.length) {
106
+ for (const routerRes of routeInfo.responseMetadata) {
93
107
  switch (routerRes.type) {
94
108
  case decorator_1.WEB_RESPONSE_HTTP_CODE:
95
109
  res.status(routerRes.code);
@@ -106,66 +120,59 @@ class MidwayExpressFramework extends core_1.BaseFramework {
106
120
  }
107
121
  }
108
122
  }
109
- res.send(result);
123
+ const { result: returnValue, error } = await this.filterManager.runResultFilter(result, req, res, next);
124
+ if (error) {
125
+ throw error;
126
+ }
127
+ res.send(returnValue);
110
128
  };
111
129
  }
112
130
  async loadMidwayController() {
113
- const collector = new core_1.WebRouterCollector();
131
+ const collector = new core_1.WebRouterCollector('', {
132
+ globalPrefix: this.configurationOptions.globalPrefix,
133
+ });
114
134
  const routerTable = await collector.getRouterTable();
115
135
  const routerList = await collector.getRoutePriorityList();
116
136
  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}`);
137
+ // bind controller first
138
+ this.getApplicationContext().bindClass(routerInfo.routerModule);
139
+ this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
124
140
  // new router
125
141
  const newRouter = this.createRouter(routerInfo.routerOptions);
126
142
  // add router middleware
127
- await this.handlerWebMiddleware(routerInfo.middleware, (middlewareImpl) => {
143
+ await this.handlerWebMiddleware(routerInfo.middleware, middlewareImpl => {
128
144
  newRouter.use(middlewareImpl);
129
145
  });
130
146
  // add route
131
147
  const routes = routerTable.get(routerInfo.prefix);
132
148
  for (const routeInfo of routes) {
133
149
  // router middleware
134
- await this.handlerWebMiddleware(routeInfo.middleware, (middlewareImpl) => {
150
+ await this.handlerWebMiddleware(routeInfo.middleware, middlewareImpl => {
135
151
  newRouter.use(middlewareImpl);
136
152
  });
137
153
  this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
138
154
  // apply controller from request context
139
- newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, this.generateController(routeInfo.handlerName, routeInfo.requestMetadata, routeInfo.responseMetadata));
155
+ newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, this.generateController(routeInfo));
140
156
  }
141
157
  this.app.use(routerInfo.prefix, newRouter);
142
158
  }
143
159
  }
144
- async generateMiddleware(middlewareId) {
145
- const mwIns = await this.getApplicationContext().getAsync(middlewareId);
146
- return mwIns.resolve();
147
- }
148
160
  /**
149
- * @param controllerOption
161
+ * @param routerOptions
150
162
  */
151
163
  createRouter(routerOptions) {
152
164
  return express.Router({ caseSensitive: routerOptions.sensitive });
153
165
  }
154
166
  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
- }
167
+ const fn = await this.expressMiddlewareService.compose(middlewares);
168
+ handlerCallback(fn);
169
+ }
170
+ async getMiddleware() {
171
+ if (!this.composeMiddleware) {
172
+ this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager);
173
+ await this.filterManager.init(this.applicationContext);
168
174
  }
175
+ return this.composeMiddleware;
169
176
  }
170
177
  async beforeStop() {
171
178
  this.server.close();
@@ -179,6 +186,13 @@ class MidwayExpressFramework extends core_1.BaseFramework {
179
186
  getDefaultContextLoggerClass() {
180
187
  return logger_1.MidwayExpressContextLogger;
181
188
  }
182
- }
189
+ };
190
+ __decorate([
191
+ (0, decorator_1.Inject)(),
192
+ __metadata("design:type", middlewareService_1.MidwayExpressMiddlewareService)
193
+ ], MidwayExpressFramework.prototype, "expressMiddlewareService", void 0);
194
+ MidwayExpressFramework = __decorate([
195
+ (0, decorator_1.Framework)()
196
+ ], MidwayExpressFramework);
183
197
  exports.MidwayExpressFramework = MidwayExpressFramework;
184
198
  //# 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,27 +1,19 @@
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";
5
- /**
6
- * @deprecated use Request from express
7
- */
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
- }>;
2
+ import { CommonMiddlewareUnion, ContextMiddlewareManager, IConfigurationOptions, IMiddleware, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
3
+ import { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request, Response } from 'express';
4
+ export declare type IMidwayExpressContext = IMidwayContext<Request>;
5
+ export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, ExpressNextFunction>;
6
+ export interface IMidwayExpressApplication extends IMidwayApplication<IMidwayExpressContext, ExpressApplication> {
7
+ /**
8
+ * add global middleware to app
9
+ * @param Middleware
10
+ */
11
+ useMiddleware<Response, NextFunction>(Middleware: CommonMiddlewareUnion<IMidwayExpressContext, Response, NextFunction>): void;
12
+ /**
13
+ * get global middleware
14
+ */
15
+ getMiddleware<Response, NextFunction>(): ContextMiddlewareManager<IMidwayExpressContext, Response, NextFunction>;
16
+ }
25
17
  export interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {
26
18
  /**
27
19
  * application http port
@@ -43,13 +35,22 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
43
35
  * https ca
44
36
  */
45
37
  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;
38
+ /**
39
+ * http2 support
40
+ */
41
+ http2?: boolean;
42
+ /**
43
+ * http global prefix
44
+ */
45
+ globalPrefix?: string;
51
46
  }
52
47
  export declare type Application = IMidwayExpressApplication;
48
+ export declare type NextFunction = ExpressNextFunction;
53
49
  export interface Context extends IMidwayExpressContext {
54
50
  }
51
+ declare module '@midwayjs/core/dist/interface' {
52
+ interface MidwayConfig {
53
+ express?: IMidwayExpressConfigurationOptions;
54
+ }
55
+ }
55
56
  //# 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 } from '@midwayjs/core';
2
+ import { IMidwayExpressContext } 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>, name?: string): Promise<{
8
+ (req: IMidwayExpressContext, res: Response, next: NextFunction): void;
9
+ _name: string;
10
+ }>;
11
+ }
12
+ export declare function pathMatching(options: any): (ctx?: any) => any;
13
+ //# sourceMappingURL=middlewareService.d.ts.map
@@ -0,0 +1,119 @@
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.pathMatching = 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, 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();
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 = 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 pathMatching(options) {
83
+ options = options || {};
84
+ if (options.match && options.ignore)
85
+ throw new core_1.MidwayCommonError('options.match and options.ignore can not both present');
86
+ if (!options.match && !options.ignore)
87
+ return () => true;
88
+ const matchFn = options.match
89
+ ? toPathMatch(options.match)
90
+ : toPathMatch(options.ignore);
91
+ return function pathMatch(ctx) {
92
+ const matched = matchFn(ctx);
93
+ return options.match ? matched : !matched;
94
+ };
95
+ }
96
+ exports.pathMatching = pathMatching;
97
+ function toPathMatch(pattern) {
98
+ if (typeof pattern === 'string') {
99
+ const reg = (0, core_1.pathToRegexp)(pattern, [], { end: false });
100
+ if (reg.global)
101
+ reg.lastIndex = 0;
102
+ return ctx => reg.test(ctx.path);
103
+ }
104
+ if (pattern instanceof RegExp) {
105
+ return ctx => {
106
+ if (pattern.global)
107
+ pattern.lastIndex = 0;
108
+ return pattern.test(ctx.path);
109
+ };
110
+ }
111
+ if (typeof pattern === 'function')
112
+ return pattern;
113
+ if (Array.isArray(pattern)) {
114
+ const matchs = pattern.map(item => toPathMatch(item));
115
+ return ctx => matchs.some(match => match(ctx));
116
+ }
117
+ throw new core_1.MidwayCommonError('match/ignore pattern must be RegExp, Array or String, but got ' + pattern);
118
+ }
119
+ //# 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.9+d5acc750",
3
+ "version": "3.0.0-beta.4",
4
4
  "description": "Midway Web Framework for Express",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -23,14 +23,14 @@
23
23
  ],
24
24
  "license": "MIT",
25
25
  "devDependencies": {
26
- "@midwayjs/decorator": "^3.0.0-alpha.2",
27
- "@midwayjs/mock": "^3.0.0-alpha.9+d5acc750",
26
+ "@midwayjs/decorator": "^3.0.0-beta.4",
27
+ "@midwayjs/mock": "^3.0.0-beta.4",
28
28
  "@types/express": "^4.17.8",
29
29
  "fs-extra": "^8.0.1"
30
30
  },
31
31
  "dependencies": {
32
- "@midwayjs/core": "^3.0.0-alpha.9+d5acc750",
33
- "@midwayjs/logger": "^2.11.3",
32
+ "@midwayjs/core": "^3.0.0-beta.4",
33
+ "@midwayjs/logger": "^3.0.0-beta.4",
34
34
  "express": "^4.17.1"
35
35
  },
36
36
  "author": "Harry Chen <czy88840616@gmail.com>",
@@ -38,5 +38,8 @@
38
38
  "type": "git",
39
39
  "url": "http://github.com/midwayjs/midway.git"
40
40
  },
41
- "gitHead": "d5acc7505275ea9d566edd38e5e0377141e0abc1"
41
+ "engines": {
42
+ "node": ">=12"
43
+ },
44
+ "gitHead": "02e2144e302f807770b512b0d89da3145b1cbf2e"
42
45
  }