@midwayjs/express 3.0.0-beta.1 → 3.0.0-beta.5

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,46 @@
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.5](https://github.com/midwayjs/midway/compare/v3.0.0-beta.4...v3.0.0-beta.5) (2021-11-25)
7
+
8
+ **Note:** Version bump only for package @midwayjs/express
9
+
10
+
11
+
12
+
13
+
14
+ # [3.0.0-beta.4](https://github.com/midwayjs/midway/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-11-24)
15
+
16
+
17
+ ### Features
18
+
19
+ * add i18n ([#1375](https://github.com/midwayjs/midway/issues/1375)) ([bffefe0](https://github.com/midwayjs/midway/commit/bffefe07afe45777d49b5a76b9ab17fc2b9d9a55))
20
+ * auto transform args to type ([#1372](https://github.com/midwayjs/midway/issues/1372)) ([bb3f7d2](https://github.com/midwayjs/midway/commit/bb3f7d2028a034e1926d9df554849332354c3762))
21
+ * support global prefix url ([#1371](https://github.com/midwayjs/midway/issues/1371)) ([cc5fe44](https://github.com/midwayjs/midway/commit/cc5fe44e1d221590562dc71e1f33ae96093e0da7))
22
+
23
+
24
+
25
+
26
+
27
+ # [3.0.0-beta.3](https://github.com/midwayjs/midway/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-11-18)
28
+
29
+
30
+ ### Features
31
+
32
+ * add component and framework config definition ([#1367](https://github.com/midwayjs/midway/issues/1367)) ([b2fe615](https://github.com/midwayjs/midway/commit/b2fe6157f99659471ff1333eca0b86bb889f61a3))
33
+
34
+
35
+
36
+
37
+
38
+ # [3.0.0-beta.2](https://github.com/midwayjs/midway/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-11-16)
39
+
40
+ **Note:** Version bump only for package @midwayjs/express
41
+
42
+
43
+
44
+
45
+
6
46
  # [3.0.0-beta.1](https://github.com/midwayjs/midway/compare/v2.12.4...v3.0.0-beta.1) (2021-11-14)
7
47
 
8
48
 
@@ -1,10 +1,7 @@
1
- import { MidwayExpressFramework } from './framework';
2
1
  import { MidwayDecoratorService } from '@midwayjs/core';
3
2
  export declare class ExpressConfiguration {
4
- framework: MidwayExpressFramework;
5
3
  decoratorService: MidwayDecoratorService;
6
4
  init(): void;
7
5
  onReady(): Promise<void>;
8
- onServerReady(): Promise<void>;
9
6
  }
10
7
  //# sourceMappingURL=configuration.d.ts.map
@@ -11,23 +11,15 @@ var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ExpressConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
- const framework_1 = require("./framework");
15
14
  const core_1 = require("@midwayjs/core");
16
15
  let ExpressConfiguration = class ExpressConfiguration {
17
16
  init() {
18
17
  this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
19
- return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
18
+ return (0, core_1.extractExpressLikeValue)(options.metadata.type, options.metadata.propertyData, options.originParamType)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
20
19
  });
21
20
  }
22
21
  async onReady() { }
23
- async onServerReady() {
24
- await this.framework.run();
25
- }
26
22
  };
27
- __decorate([
28
- (0, decorator_1.Inject)(),
29
- __metadata("design:type", framework_1.MidwayExpressFramework)
30
- ], ExpressConfiguration.prototype, "framework", void 0);
31
23
  __decorate([
32
24
  (0, decorator_1.Inject)(),
33
25
  __metadata("design:type", core_1.MidwayDecoratorService)
@@ -1,16 +1,12 @@
1
1
  /// <reference types="node" />
2
- import { BaseFramework, ContextMiddlewareManager, FunctionMiddleware, IMidwayBootstrapOptions, MiddlewareRespond, MidwayFrameworkType, ExceptionFilterManager } 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
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
9
  private server;
12
- protected middlewareManager: ContextMiddlewareManager<IMidwayExpressContext, Response<any, Record<string, any>>, NextFunction>;
13
- protected exceptionFilterManager: ExceptionFilterManager<IMidwayExpressContext, Response<any, Record<string, any>>, NextFunction>;
14
10
  private expressMiddlewareService;
15
11
  configure(): IMidwayExpressConfigurationOptions;
16
12
  applicationInitialize(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
@@ -18,16 +14,9 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
18
14
  getFrameworkType(): MidwayFrameworkType;
19
15
  /**
20
16
  * wrap controller string to middleware function
21
- * @param controllerMapping like FooController.index
22
- * @param routeArgsInfo
23
- * @param routerResponseData
24
17
  */
25
- generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): IRouterHandler<any>;
18
+ protected generateController(routeInfo: RouterInfo): IRouterHandler<any>;
26
19
  loadMidwayController(): Promise<void>;
27
- /**
28
- * @deprecated
29
- */
30
- generateMiddleware(middlewareId: string): Promise<FunctionMiddleware<IMidwayExpressContext, Response<any, Record<string, any>>, NextFunction>>;
31
20
  /**
32
21
  * @param routerOptions
33
22
  */
package/dist/framework.js CHANGED
@@ -16,28 +16,11 @@ const express = require("express");
16
16
  const logger_1 = require("./logger");
17
17
  const middlewareService_1 = require("./middlewareService");
18
18
  let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFramework {
19
- constructor() {
20
- super(...arguments);
21
- this.controllerIds = [];
22
- this.middlewareManager = new core_1.ContextMiddlewareManager();
23
- this.exceptionFilterManager = new core_1.ExceptionFilterManager();
24
- }
25
19
  configure() {
26
20
  return this.configService.getConfiguration('express');
27
21
  }
28
22
  async applicationInitialize(options) {
29
23
  this.app = express();
30
- this.defineApplicationProperties({
31
- generateController: (controllerMapping) => {
32
- return this.generateController(controllerMapping);
33
- },
34
- /**
35
- * @deprecated
36
- */
37
- generateMiddleware: async (middlewareId) => {
38
- return this.generateMiddleware(middlewareId);
39
- },
40
- });
41
24
  this.app.use((req, res, next) => {
42
25
  const ctx = req;
43
26
  this.app.createAnonymousContext(ctx);
@@ -46,6 +29,25 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
46
29
  ctx.requestContext.registerObject('res', res);
47
30
  next();
48
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
+ });
49
51
  // https config
50
52
  if (this.configurationOptions.key && this.configurationOptions.cert) {
51
53
  this.configurationOptions.key = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.key);
@@ -68,25 +70,6 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
68
70
  }
69
71
  // register httpServer to applicationContext
70
72
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
71
- }
72
- async run() {
73
- // use global middleware
74
- const globalMiddleware = await this.getMiddleware();
75
- this.app.use(globalMiddleware);
76
- // load controller
77
- await this.loadMidwayController();
78
- // use global error handler
79
- this.app.use(async (err, req, res, next) => {
80
- if (err) {
81
- const { result, error } = await this.exceptionFilterManager.run(err, req, res, next);
82
- if (error) {
83
- next(error);
84
- }
85
- else {
86
- res.send(result);
87
- }
88
- }
89
- });
90
73
  if (this.configurationOptions.port) {
91
74
  new Promise(resolve => {
92
75
  const args = [this.configurationOptions.port];
@@ -105,15 +88,11 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
105
88
  }
106
89
  /**
107
90
  * wrap controller string to middleware function
108
- * @param controllerMapping like FooController.index
109
- * @param routeArgsInfo
110
- * @param routerResponseData
111
91
  */
112
- generateController(controllerMapping, routeArgsInfo, routerResponseData) {
113
- const [controllerId, methodName] = controllerMapping.split('.');
92
+ generateController(routeInfo) {
114
93
  return async (req, res, next) => {
115
- const controller = await req.requestContext.getAsync(controllerId);
116
- const result = await controller[methodName].call(controller, req, res, next);
94
+ const controller = await req.requestContext.getAsync(routeInfo.id);
95
+ const result = await controller[routeInfo.method].call(controller, req, res, next);
117
96
  if (res.headersSent) {
118
97
  // return when response send
119
98
  return;
@@ -122,8 +101,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
122
101
  res.status(204);
123
102
  }
124
103
  // implement response decorator
125
- if (Array.isArray(routerResponseData) && routerResponseData.length) {
126
- for (const routerRes of routerResponseData) {
104
+ if (Array.isArray(routeInfo.responseMetadata) &&
105
+ routeInfo.responseMetadata.length) {
106
+ for (const routerRes of routeInfo.responseMetadata) {
127
107
  switch (routerRes.type) {
128
108
  case decorator_1.WEB_RESPONSE_HTTP_CODE:
129
109
  res.status(routerRes.code);
@@ -140,50 +120,43 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
140
120
  }
141
121
  }
142
122
  }
143
- 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);
144
128
  };
145
129
  }
146
130
  async loadMidwayController() {
147
- const collector = new core_1.WebRouterCollector();
131
+ const collector = new core_1.WebRouterCollector('', {
132
+ globalPrefix: this.configurationOptions.globalPrefix,
133
+ });
148
134
  const routerTable = await collector.getRouterTable();
149
135
  const routerList = await collector.getRoutePriorityList();
150
136
  for (const routerInfo of routerList) {
151
137
  // bind controller first
152
138
  this.getApplicationContext().bindClass(routerInfo.routerModule);
153
- const providerId = routerInfo.controllerId;
154
- // controller id check
155
- if (this.controllerIds.indexOf(providerId) > -1) {
156
- throw new Error(`Controller identifier [${providerId}] already exists!`);
157
- }
158
- this.controllerIds.push(providerId);
159
- this.logger.debug(`Load Controller "${providerId}", prefix=${routerInfo.prefix}`);
139
+ this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
160
140
  // new router
161
141
  const newRouter = this.createRouter(routerInfo.routerOptions);
162
142
  // add router middleware
163
- await this.handlerWebMiddleware(routerInfo.middleware, (middlewareImpl) => {
143
+ await this.handlerWebMiddleware(routerInfo.middleware, middlewareImpl => {
164
144
  newRouter.use(middlewareImpl);
165
145
  });
166
146
  // add route
167
147
  const routes = routerTable.get(routerInfo.prefix);
168
148
  for (const routeInfo of routes) {
169
149
  // router middleware
170
- await this.handlerWebMiddleware(routeInfo.middleware, (middlewareImpl) => {
150
+ await this.handlerWebMiddleware(routeInfo.middleware, middlewareImpl => {
171
151
  newRouter.use(middlewareImpl);
172
152
  });
173
153
  this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
174
154
  // apply controller from request context
175
- 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));
176
156
  }
177
157
  this.app.use(routerInfo.prefix, newRouter);
178
158
  }
179
159
  }
180
- /**
181
- * @deprecated
182
- */
183
- async generateMiddleware(middlewareId) {
184
- const mwIns = await this.getApplicationContext().getAsync(middlewareId);
185
- return mwIns.resolve();
186
- }
187
160
  /**
188
161
  * @param routerOptions
189
162
  */
@@ -197,7 +170,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
197
170
  async getMiddleware() {
198
171
  if (!this.composeMiddleware) {
199
172
  this.composeMiddleware = await this.expressMiddlewareService.compose(this.middlewareManager);
200
- await this.exceptionFilterManager.init(this.applicationContext);
173
+ await this.filterManager.init(this.applicationContext);
201
174
  }
202
175
  return this.composeMiddleware;
203
176
  }
@@ -1,16 +1,19 @@
1
1
  /// <reference types="node" />
2
- import { IConfigurationOptions, IMiddleware, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
3
- import { Application as ExpressApplication, NextFunction, Request, Response } 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';
5
4
  export declare type IMidwayExpressContext = IMidwayContext<Request>;
6
- export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, NextFunction>;
7
- export declare type IMidwayExpressApplication = IMidwayApplication<IMidwayExpressContext, ExpressApplication & {
8
- generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): IMidwayExpressMiddleware;
5
+ export declare type IMidwayExpressMiddleware = IMiddleware<IMidwayExpressContext, Response, ExpressNextFunction>;
6
+ export interface IMidwayExpressApplication extends IMidwayApplication<IMidwayExpressContext, ExpressApplication> {
9
7
  /**
10
- * @deprecated
8
+ * add global middleware to app
9
+ * @param Middleware
11
10
  */
12
- generateMiddleware(middlewareId: string): Promise<IMidwayExpressMiddleware>;
13
- }>;
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
+ }
14
17
  export interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {
15
18
  /**
16
19
  * application http port
@@ -36,8 +39,18 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
36
39
  * http2 support
37
40
  */
38
41
  http2?: boolean;
42
+ /**
43
+ * http global prefix
44
+ */
45
+ globalPrefix?: string;
39
46
  }
40
47
  export declare type Application = IMidwayExpressApplication;
48
+ export declare type NextFunction = ExpressNextFunction;
41
49
  export interface Context extends IMidwayExpressContext {
42
50
  }
51
+ declare module '@midwayjs/core/dist/interface' {
52
+ interface MidwayConfig {
53
+ express?: IMidwayExpressConfigurationOptions;
54
+ }
55
+ }
43
56
  //# sourceMappingURL=interface.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/express",
3
- "version": "3.0.0-beta.1",
3
+ "version": "3.0.0-beta.5",
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-beta.1",
27
- "@midwayjs/mock": "^3.0.0-beta.1",
26
+ "@midwayjs/decorator": "^3.0.0-beta.5",
27
+ "@midwayjs/mock": "^3.0.0-beta.5",
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-beta.1",
33
- "@midwayjs/logger": "^3.0.0-beta.1",
32
+ "@midwayjs/core": "^3.0.0-beta.5",
33
+ "@midwayjs/logger": "^3.0.0-beta.5",
34
34
  "express": "^4.17.1"
35
35
  },
36
36
  "author": "Harry Chen <czy88840616@gmail.com>",
@@ -41,5 +41,5 @@
41
41
  "engines": {
42
42
  "node": ">=12"
43
43
  },
44
- "gitHead": "72e4d20c678e65a5440c4e9a6d3b70046daa497c"
44
+ "gitHead": "ab0bf05ae6d13f6435db2f7223202be61d585a1b"
45
45
  }