@midwayjs/express 4.0.0-beta.1 → 4.0.0-beta.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
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.
package/README.md CHANGED
@@ -9,4 +9,4 @@ Document: [https://midwayjs.org](https://midwayjs.org)
9
9
 
10
10
  ## License
11
11
 
12
- [MIT]((https://github.com/midwayjs/midway/blob/master/LICENSE))
12
+ [MIT](https://github.com/midwayjs/midway/blob/master/LICENSE)
@@ -31,5 +31,7 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
31
31
  getServer(): Server;
32
32
  getPort(): string;
33
33
  getFrameworkName(): string;
34
+ private createVersioningMiddleware;
35
+ private extractVersion;
34
36
  }
35
37
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -31,6 +31,12 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
31
31
  ctx.requestContext.registerObject('res', res);
32
32
  next();
33
33
  });
34
+ // 版本控制配置
35
+ const versioningConfig = this.configurationOptions.versioning;
36
+ // 如果启用版本控制,添加版本处理中间件
37
+ if (versioningConfig?.enabled) {
38
+ this.app.use(this.createVersioningMiddleware(versioningConfig));
39
+ }
34
40
  this.defineApplicationProperties({
35
41
  useMiddleware: (routerPath, ...middleware) => {
36
42
  if (typeof routerPath === 'string' && middleware) {
@@ -139,18 +145,27 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
139
145
  }
140
146
  // register httpServer to applicationContext
141
147
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
142
- const customPort = process.env.MIDWAY_HTTP_PORT ?? this.configurationOptions.port;
143
- if (customPort) {
148
+ this.configurationOptions.listenOptions = {
149
+ port: this.configurationOptions.port,
150
+ host: this.configurationOptions.hostname,
151
+ ...this.configurationOptions.listenOptions,
152
+ };
153
+ // set port and listen server
154
+ let customPort = process.env.MIDWAY_HTTP_PORT ||
155
+ this.configurationOptions.listenOptions.port;
156
+ if (customPort === 0 || customPort === '0') {
157
+ customPort = await (0, util_2.getFreePort)();
158
+ this.logger.info(`[midway:express] detect available port: ${customPort}`);
159
+ }
160
+ this.configurationOptions.listenOptions.port = Number(customPort);
161
+ if (this.configurationOptions.listenOptions.port) {
144
162
  new Promise(resolve => {
145
- const args = [customPort];
146
- if (this.configurationOptions.hostname) {
147
- args.push(this.configurationOptions.hostname);
148
- }
149
- args.push(() => {
163
+ // 使用 ListenOptions 对象启动服务器
164
+ this.server.listen(this.configurationOptions.listenOptions, () => {
150
165
  resolve();
151
166
  });
152
- this.server.listen(...args);
153
- process.env.MIDWAY_HTTP_PORT = String(customPort);
167
+ process.env.MIDWAY_HTTP_PORT = String(this.configurationOptions.listenOptions.port);
168
+ this.logger.debug(`[midway:express] Server listening on http://${this.configurationOptions.hostname || 'localhost'}:${customPort}`);
154
169
  });
155
170
  }
156
171
  }
@@ -221,7 +236,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
221
236
  for (const routerInfo of routerList) {
222
237
  // bind controller first
223
238
  this.getApplicationContext().bindClass(routerInfo.routerModule);
224
- this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
239
+ this.logger.debug(`[midway:express] Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
225
240
  // new router
226
241
  const newRouter = this.createRouter(routerInfo.routerOptions);
227
242
  routerInfo.middleware = routerInfo.middleware ?? [];
@@ -240,9 +255,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
240
255
  const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
241
256
  routeMiddlewareList.push(routeMiddlewareFn);
242
257
  }
243
- this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
258
+ this.logger.debug(`[midway:express] Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
244
259
  // apply controller from request context
245
- newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
260
+ newRouter[routeInfo.requestMethod.toLowerCase()].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
246
261
  }
247
262
  routerMiddlewares.push({
248
263
  prefix: routerInfo.prefix,
@@ -271,7 +286,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
271
286
  if (this.server) {
272
287
  new Promise(resolve => {
273
288
  this.server.close(resolve);
289
+ process.env.MIDWAY_HTTP_PORT = '';
274
290
  });
291
+ this.logger.debug('[midway:express] server close');
275
292
  }
276
293
  }
277
294
  getServer() {
@@ -283,6 +300,53 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
283
300
  getFrameworkName() {
284
301
  return 'express';
285
302
  }
303
+ createVersioningMiddleware(config) {
304
+ return (req, res, next) => {
305
+ // 提取版本信息
306
+ const version = this.extractVersion(req, config);
307
+ req.apiVersion = version;
308
+ // 对于 URI 版本控制,重写路径
309
+ if (config.type === 'URI' && version) {
310
+ const versionPrefix = `/${config.prefix || 'v'}${version}`;
311
+ if (req.path.startsWith(versionPrefix)) {
312
+ req.originalPath = req.path;
313
+ // Express 中需要修改 url 而不是 path
314
+ req.url = req.url.replace(versionPrefix, '') || '/';
315
+ }
316
+ }
317
+ next();
318
+ };
319
+ }
320
+ extractVersion(req, config) {
321
+ // 自定义提取函数优先
322
+ if (config.extractVersionFn) {
323
+ return config.extractVersionFn(req);
324
+ }
325
+ const type = config.type || 'URI';
326
+ switch (type) {
327
+ case 'HEADER': {
328
+ const headerName = config.header || 'x-api-version';
329
+ const headerValue = req.headers[headerName];
330
+ if (typeof headerValue === 'string') {
331
+ return headerValue.replace(/^v/, '');
332
+ }
333
+ return undefined;
334
+ }
335
+ case 'MEDIA_TYPE': {
336
+ const accept = req.headers.accept;
337
+ const paramName = config.mediaTypeParam || 'version';
338
+ const match = accept?.match(new RegExp(`${paramName}=(\\\\d+)`));
339
+ return match ? match[1] : undefined;
340
+ }
341
+ case 'URI': {
342
+ const prefix = config.prefix || 'v';
343
+ const uriMatch = req.path.match(new RegExp(`^/${prefix}(\\\\d+)`));
344
+ return uriMatch ? uriMatch[1] : undefined;
345
+ }
346
+ default:
347
+ return config.defaultVersion;
348
+ }
349
+ }
286
350
  };
287
351
  exports.MidwayExpressFramework = MidwayExpressFramework;
288
352
  exports.MidwayExpressFramework = MidwayExpressFramework = __decorate([
@@ -1,11 +1,21 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
+ /// <reference types="node" />
3
4
  import { CommonMiddlewareUnion, ContextMiddlewareManager, FunctionMiddleware, IConfigurationOptions, IMiddleware, IMidwayApplication, IMidwayContext } from '@midwayjs/core';
4
5
  import { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request as ExpressRequest, Response as ExpressResponse } from 'express';
6
+ import { ListenOptions } from 'net';
5
7
  type Request = IMidwayContext<ExpressRequest>;
6
8
  export type Response = ExpressResponse;
7
9
  export type NextFunction = ExpressNextFunction;
8
10
  export interface Context extends Request {
11
+ /**
12
+ * API version extracted from request
13
+ */
14
+ apiVersion?: string;
15
+ /**
16
+ * Original path before version processing
17
+ */
18
+ originalPath?: string;
9
19
  }
10
20
  /**
11
21
  * @deprecated use Context
@@ -70,6 +80,43 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
70
80
  * https/https/http2 server options
71
81
  */
72
82
  serverOptions?: Record<string, any>;
83
+ /**
84
+ * listen options
85
+ */
86
+ listenOptions?: ListenOptions;
87
+ /**
88
+ * API versioning configuration
89
+ */
90
+ versioning?: {
91
+ /**
92
+ * Enable versioning
93
+ */
94
+ enabled: boolean;
95
+ /**
96
+ * Versioning type
97
+ */
98
+ type?: 'URI' | 'HEADER' | 'MEDIA_TYPE' | 'CUSTOM';
99
+ /**
100
+ * Default version if none is specified
101
+ */
102
+ defaultVersion?: string;
103
+ /**
104
+ * Version prefix for URI versioning (default: 'v')
105
+ */
106
+ prefix?: string;
107
+ /**
108
+ * Header name for HEADER versioning (default: 'x-api-version')
109
+ */
110
+ header?: string;
111
+ /**
112
+ * Media type parameter name for MEDIA_TYPE versioning (default: 'version')
113
+ */
114
+ mediaTypeParam?: string;
115
+ /**
116
+ * Custom version extraction function
117
+ */
118
+ extractVersionFn?: (ctx: Context) => string | undefined;
119
+ };
73
120
  }
74
121
  export type Application = IMidwayExpressApplication;
75
122
  export {};
package/dist/util.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export declare function sendData(res: any, data: any): void;
2
+ export declare function getFreePort(): Promise<number>;
2
3
  //# sourceMappingURL=util.d.ts.map
package/dist/util.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sendData = void 0;
3
+ exports.getFreePort = exports.sendData = void 0;
4
+ const net_1 = require("net");
4
5
  function sendData(res, data) {
5
6
  if (typeof data === 'number') {
6
7
  res.status(res.statusCode).send('' + data);
@@ -10,4 +11,20 @@ function sendData(res, data) {
10
11
  }
11
12
  }
12
13
  exports.sendData = sendData;
14
+ async function getFreePort() {
15
+ return new Promise((resolve, reject) => {
16
+ const server = (0, net_1.createServer)();
17
+ server.listen(0, () => {
18
+ try {
19
+ const port = server.address().port;
20
+ server.close();
21
+ resolve(port);
22
+ }
23
+ catch (err) {
24
+ reject(err);
25
+ }
26
+ });
27
+ });
28
+ }
29
+ exports.getFreePort = getFreePort;
13
30
  //# sourceMappingURL=util.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/express",
3
- "version": "4.0.0-beta.1",
3
+ "version": "4.0.0-beta.3",
4
4
  "description": "Midway Web Framework for Express",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
@@ -24,14 +24,14 @@
24
24
  ],
25
25
  "license": "MIT",
26
26
  "devDependencies": {
27
- "@midwayjs/core": "^4.0.0-beta.1",
28
- "@midwayjs/mock": "^4.0.0-beta.1",
29
- "@types/body-parser": "1.19.5",
30
- "@types/express": "4.17.21",
27
+ "@midwayjs/core": "^4.0.0-beta.3",
28
+ "@midwayjs/mock": "^4.0.0-beta.3",
29
+ "@types/body-parser": "1.19.6",
30
+ "@types/express": "4.17.23",
31
31
  "fs-extra": "11.3.0"
32
32
  },
33
33
  "dependencies": {
34
- "@midwayjs/express-session": "^4.0.0-beta.1",
34
+ "@midwayjs/express-session": "^4.0.0-beta.3",
35
35
  "body-parser": "1.20.3",
36
36
  "cookie-parser": "^1.4.6",
37
37
  "express": "4.21.2"
@@ -42,7 +42,7 @@
42
42
  "url": "https://github.com/midwayjs/midway.git"
43
43
  },
44
44
  "engines": {
45
- "node": ">=12"
45
+ "node": ">=20"
46
46
  },
47
- "gitHead": "832961ec3aff123c033197d8c00cb2bc9bad7ff8"
47
+ "gitHead": "b5b7dfaafb81823cdba5fd10ad2709b3e495c6b4"
48
48
  }