@midwayjs/express 4.0.0-alpha.1 → 4.0.0-beta.2

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/README.md CHANGED
@@ -9,4 +9,4 @@ Document: [https://midwayjs.org](https://midwayjs.org)
9
9
 
10
10
  ## License
11
11
 
12
- [MIT]((http://github.com/midwayjs/midway/blob/master/LICENSE))
12
+ [MIT]((https://github.com/midwayjs/midway/blob/master/LICENSE))
@@ -1,7 +1,12 @@
1
1
  import { Options, OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';
2
2
  import { CookieOptions } from 'express';
3
- export declare const express: {
4
- contextLoggerFormat: (info: any) => string;
3
+ export declare const express: {};
4
+ export declare const midwayLogger: {
5
+ clients: {
6
+ appLogger: {
7
+ contextFormat: (info: any) => string;
8
+ };
9
+ };
5
10
  };
6
11
  export declare const cookieParser: {
7
12
  enable?: boolean;
@@ -1,25 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.bodyParser = exports.cookieParser = exports.express = void 0;
4
- exports.express = {
5
- contextLoggerFormat: info => {
6
- const req = info.ctx;
7
- // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
8
- const userId = req?.['session']?.['userId'] || '-';
9
- const traceId = req.traceId ?? '-';
10
- const use = Date.now() - info.ctx.startTime;
11
- const label = userId +
12
- '/' +
13
- req.ip +
14
- '/' +
15
- traceId +
16
- '/' +
17
- use +
18
- 'ms ' +
19
- req.method +
20
- ' ' +
21
- req.url;
22
- return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
3
+ exports.bodyParser = exports.cookieParser = exports.midwayLogger = exports.express = void 0;
4
+ exports.express = {};
5
+ exports.midwayLogger = {
6
+ clients: {
7
+ appLogger: {
8
+ contextFormat: info => {
9
+ const req = info.ctx;
10
+ // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
11
+ const userId = req?.['session']?.['userId'] || '-';
12
+ const traceId = req.traceId ?? '-';
13
+ const use = Date.now() - info.ctx.startTime;
14
+ const label = userId +
15
+ '/' +
16
+ req.ip +
17
+ '/' +
18
+ traceId +
19
+ '/' +
20
+ use +
21
+ 'ms ' +
22
+ req.method +
23
+ ' ' +
24
+ req.url;
25
+ return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
26
+ },
27
+ },
23
28
  },
24
29
  };
25
30
  exports.cookieParser = {
package/dist/framework.js CHANGED
@@ -118,9 +118,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
118
118
  };
119
119
  // https config
120
120
  if (serverOptions.key && serverOptions.cert) {
121
- serverOptions.key = core_1.PathFileUtil.getFileContentSync(serverOptions.key);
122
- serverOptions.cert = core_1.PathFileUtil.getFileContentSync(serverOptions.cert);
123
- serverOptions.ca = core_1.PathFileUtil.getFileContentSync(serverOptions.ca);
121
+ serverOptions.key = core_1.PathFileUtils.getFileContentSync(serverOptions.key);
122
+ serverOptions.cert = core_1.PathFileUtils.getFileContentSync(serverOptions.cert);
123
+ serverOptions.ca = core_1.PathFileUtils.getFileContentSync(serverOptions.ca);
124
124
  process.env.MIDWAY_HTTP_SSL = 'true';
125
125
  if (serverOptions.http2) {
126
126
  this.server = require('http2').createSecureServer(serverOptions, this.app);
@@ -139,18 +139,27 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
139
139
  }
140
140
  // register httpServer to applicationContext
141
141
  this.applicationContext.registerObject(core_1.HTTP_SERVER_KEY, this.server);
142
- const customPort = process.env.MIDWAY_HTTP_PORT ?? this.configurationOptions.port;
143
- if (customPort) {
142
+ this.configurationOptions.listenOptions = {
143
+ port: this.configurationOptions.port,
144
+ host: this.configurationOptions.hostname,
145
+ ...this.configurationOptions.listenOptions,
146
+ };
147
+ // set port and listen server
148
+ let customPort = process.env.MIDWAY_HTTP_PORT ||
149
+ this.configurationOptions.listenOptions.port;
150
+ if (customPort === 0 || customPort === '0') {
151
+ customPort = await (0, util_2.getFreePort)();
152
+ this.logger.info(`[midway:express] detect available port: ${customPort}`);
153
+ }
154
+ this.configurationOptions.listenOptions.port = Number(customPort);
155
+ if (this.configurationOptions.listenOptions.port) {
144
156
  new Promise(resolve => {
145
- const args = [customPort];
146
- if (this.configurationOptions.hostname) {
147
- args.push(this.configurationOptions.hostname);
148
- }
149
- args.push(() => {
157
+ // 使用 ListenOptions 对象启动服务器
158
+ this.server.listen(this.configurationOptions.listenOptions, () => {
150
159
  resolve();
151
160
  });
152
- this.server.listen(...args);
153
- process.env.MIDWAY_HTTP_PORT = String(customPort);
161
+ process.env.MIDWAY_HTTP_PORT = String(this.configurationOptions.listenOptions.port);
162
+ this.logger.debug(`[midway:express] Server listening on http://${this.configurationOptions.hostname || 'localhost'}:${customPort}`);
154
163
  });
155
164
  }
156
165
  }
@@ -221,7 +230,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
221
230
  for (const routerInfo of routerList) {
222
231
  // bind controller first
223
232
  this.getApplicationContext().bindClass(routerInfo.routerModule);
224
- this.logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
233
+ this.logger.debug(`[midway:express] Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
225
234
  // new router
226
235
  const newRouter = this.createRouter(routerInfo.routerOptions);
227
236
  routerInfo.middleware = routerInfo.middleware ?? [];
@@ -240,9 +249,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
240
249
  const routeMiddlewareFn = await this.expressMiddlewareService.compose(routeInfo.middleware, this.app);
241
250
  routeMiddlewareList.push(routeMiddlewareFn);
242
251
  }
243
- this.logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
252
+ this.logger.debug(`[midway:express] Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
244
253
  // apply controller from request context
245
- newRouter[routeInfo.requestMethod].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
254
+ newRouter[routeInfo.requestMethod.toLowerCase()].call(newRouter, routeInfo.url, ...routeMiddlewareList, this.generateController(routeInfo));
246
255
  }
247
256
  routerMiddlewares.push({
248
257
  prefix: routerInfo.prefix,
@@ -271,7 +280,9 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
271
280
  if (this.server) {
272
281
  new Promise(resolve => {
273
282
  this.server.close(resolve);
283
+ process.env.MIDWAY_HTTP_PORT = '';
274
284
  });
285
+ this.logger.debug('[midway:express] server close');
275
286
  }
276
287
  }
277
288
  getServer() {
@@ -1,7 +1,9 @@
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;
@@ -70,6 +72,10 @@ export interface IMidwayExpressConfigurationOptions extends IConfigurationOption
70
72
  * https/https/http2 server options
71
73
  */
72
74
  serverOptions?: Record<string, any>;
75
+ /**
76
+ * listen options
77
+ */
78
+ listenOptions?: ListenOptions;
73
79
  }
74
80
  export type Application = IMidwayExpressApplication;
75
81
  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-alpha.1",
3
+ "version": "4.0.0-beta.2",
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-alpha.1",
28
- "@midwayjs/mock": "^4.0.0-alpha.1",
27
+ "@midwayjs/core": "^4.0.0-beta.2",
28
+ "@midwayjs/mock": "^4.0.0-beta.2",
29
29
  "@types/body-parser": "1.19.5",
30
- "@types/express": "4.17.21",
31
- "fs-extra": "11.2.0"
30
+ "@types/express": "4.17.23",
31
+ "fs-extra": "11.3.0"
32
32
  },
33
33
  "dependencies": {
34
- "@midwayjs/express-session": "^4.0.0-alpha.1",
34
+ "@midwayjs/express-session": "^4.0.0-beta.2",
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": "14bb4da91805a1cf52f190c0d37a74b395dd6372"
47
+ "gitHead": "53bfef4c5279da5f09025e4610bdbf64f94f60bd"
48
48
  }