@midwayjs/express 3.0.2 → 3.0.6

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.
@@ -1,5 +1,8 @@
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;
5
+ };
3
6
  export declare const cookieParser: {
4
7
  secret?: string | string[];
5
8
  options?: CookieOptions;
@@ -1,6 +1,28 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.bodyParser = exports.cookieParser = void 0;
3
+ exports.bodyParser = exports.cookieParser = exports.express = void 0;
4
+ exports.express = {
5
+ contextLoggerFormat: info => {
6
+ var _a;
7
+ const req = info.ctx;
8
+ // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
9
+ const userId = ((_a = req === null || req === void 0 ? void 0 : req['session']) === null || _a === void 0 ? void 0 : _a['userId']) || '-';
10
+ const traceId = '-';
11
+ const use = Date.now() - info.ctx.startTime;
12
+ const label = userId +
13
+ '/' +
14
+ req.ip +
15
+ '/' +
16
+ traceId +
17
+ '/' +
18
+ use +
19
+ 'ms ' +
20
+ req.method +
21
+ ' ' +
22
+ req.url;
23
+ return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
24
+ },
25
+ };
4
26
  exports.cookieParser = {};
5
27
  exports.bodyParser = {
6
28
  enable: true,
@@ -3,7 +3,6 @@ import { BaseFramework, IMidwayBootstrapOptions, MiddlewareRespond, MidwayFramew
3
3
  import { IMidwayExpressApplication, IMidwayExpressConfigurationOptions, Context } from './interface';
4
4
  import type { IRouter, IRouterHandler, Response, NextFunction } from 'express';
5
5
  import { Server } from 'net';
6
- import { MidwayExpressContextLogger } from './logger';
7
6
  export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpressApplication, Context, IMidwayExpressConfigurationOptions, Response, NextFunction> {
8
7
  app: IMidwayExpressApplication;
9
8
  private server;
@@ -31,6 +30,5 @@ export declare class MidwayExpressFramework extends BaseFramework<IMidwayExpress
31
30
  getServer(): Server;
32
31
  getPort(): string;
33
32
  getFrameworkName(): string;
34
- getDefaultContextLoggerClass(): typeof MidwayExpressContextLogger;
35
33
  }
36
34
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -10,7 +10,6 @@ exports.MidwayExpressFramework = void 0;
10
10
  const core_1 = require("@midwayjs/core");
11
11
  const decorator_1 = require("@midwayjs/decorator");
12
12
  const express = require("express");
13
- const logger_1 = require("./logger");
14
13
  const middlewareService_1 = require("./middlewareService");
15
14
  const util_1 = require("util");
16
15
  const util_2 = require("./util");
@@ -57,7 +56,7 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
57
56
  debug('[express]: use 404 not found middleware');
58
57
  // eslint-disable-next-line
59
58
  this.app.use(function notFound(req, res, next) {
60
- next(new core_1.httpError.NotFoundError());
59
+ next(new core_1.httpError.NotFoundError(`${req.path} Not Found`));
61
60
  });
62
61
  debug('[express]: use global error handler middleware');
63
62
  // use global error handler
@@ -246,9 +245,6 @@ let MidwayExpressFramework = class MidwayExpressFramework extends core_1.BaseFra
246
245
  getFrameworkName() {
247
246
  return 'midway:express';
248
247
  }
249
- getDefaultContextLoggerClass() {
250
- return logger_1.MidwayExpressContextLogger;
251
- }
252
248
  };
253
249
  MidwayExpressFramework = __decorate([
254
250
  (0, decorator_1.Framework)()
package/dist/index.d.ts CHANGED
@@ -2,5 +2,4 @@ export * from './interface';
2
2
  export { MidwayExpressFramework as Framework } from './framework';
3
3
  export { ExpressConfiguration as Configuration } from './configuration';
4
4
  export * from './middlewareService';
5
- export * from './logger';
6
5
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -17,5 +17,4 @@ Object.defineProperty(exports, "Framework", { enumerable: true, get: function ()
17
17
  var configuration_1 = require("./configuration");
18
18
  Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.ExpressConfiguration; } });
19
19
  __exportStar(require("./middlewareService"), exports);
20
- __exportStar(require("./logger"), exports);
21
20
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/express",
3
- "version": "3.0.2",
3
+ "version": "3.0.6",
4
4
  "description": "Midway Web Framework for Express",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -19,21 +19,20 @@
19
19
  ],
20
20
  "files": [
21
21
  "dist/**/*.js",
22
- "dist/**/*.d.ts",
23
- "dist/**/*.js.map"
22
+ "dist/**/*.d.ts"
24
23
  ],
25
24
  "license": "MIT",
26
25
  "devDependencies": {
27
- "@midwayjs/decorator": "^3.0.2",
28
- "@midwayjs/logger": "^2.14.0",
29
- "@midwayjs/mock": "^3.0.2",
26
+ "@midwayjs/decorator": "^3.0.6",
27
+ "@midwayjs/logger": "^2.15.0",
28
+ "@midwayjs/mock": "^3.0.6",
30
29
  "@types/body-parser": "1.19.2",
31
30
  "@types/express": "4.17.13",
32
31
  "fs-extra": "10.0.0"
33
32
  },
34
33
  "dependencies": {
35
- "@midwayjs/core": "^3.0.2",
36
- "@midwayjs/express-session": "^3.0.2",
34
+ "@midwayjs/core": "^3.0.6",
35
+ "@midwayjs/express-session": "^3.0.6",
37
36
  "body-parser": "1.19.1",
38
37
  "cookie-parser": "^1.4.6",
39
38
  "express": "4.17.2"
@@ -46,5 +45,5 @@
46
45
  "engines": {
47
46
  "node": ">=12"
48
47
  },
49
- "gitHead": "ca77247d229978a736e79bb208579c014ed226fc"
48
+ "gitHead": "afaa5b59a2be85e915233a9268c0e05965dd5c61"
50
49
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.default.js","sourceRoot":"","sources":["../../src/config/config.default.ts"],"names":[],"mappings":";;;AAQa,QAAA,YAAY,GAGrB,EAAE,CAAC;AAEM,QAAA,UAAU,GAcnB;IACF,MAAM,EAAE,IAAI;IACZ,IAAI,EAAE;QACJ,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,IAAI;KACb;IACD,GAAG,EAAE;QACH,MAAM,EAAE,KAAK;QACb,KAAK,EAAE,KAAK;KACb;IACD,IAAI,EAAE;QACJ,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,KAAK;KACb;IACD,UAAU,EAAE;QACV,MAAM,EAAE,IAAI;QACZ,QAAQ,EAAE,KAAK;QACf,KAAK,EAAE,KAAK;QACZ,cAAc,EAAE,IAAI;KACrB;CACF,CAAC","sourcesContent":["import {\n Options,\n OptionsJson,\n OptionsText,\n OptionsUrlencoded,\n} from 'body-parser';\nimport { CookieOptions } from 'express';\n\nexport const cookieParser: {\n secret?: string | string[];\n options?: CookieOptions;\n} = {};\n\nexport const bodyParser: {\n enable?: boolean;\n json?: OptionsJson & {\n enable?: boolean;\n };\n raw?: Options & {\n enable?: boolean;\n };\n text?: OptionsText & {\n enable?: boolean;\n };\n urlencoded?: OptionsUrlencoded & {\n enable?: boolean;\n };\n} = {\n enable: true,\n json: {\n enable: true,\n limit: '1mb',\n strict: true,\n },\n raw: {\n enable: false,\n limit: '1mb',\n },\n text: {\n enable: true,\n limit: '1mb',\n },\n urlencoded: {\n enable: true,\n extended: false,\n limit: '1mb',\n parameterLimit: 1000,\n },\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mDAK6B;AAC7B,yCAIwB;AACxB,qDAAqD;AACrD,2CAAqD;AACrD,0CAA0C;AAC1C,8CAA8C;AAC9C,yDAAyD;AAWzD,IAAa,oBAAoB,GAAjC,MAAa,oBAAoB;IAW/B,IAAI;QACF,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,CAC5C,gCAAoB,EACpB,OAAO,CAAC,EAAE;YACR,OAAO,IAAA,8BAAuB,EAC5B,OAAO,CAAC,QAAQ,CAAC,I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AAa,CACjC,UAAU,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CACvC,CAAC;aACH;YACD,kDAAkD;YAClD,IAAI,gBAAgB,CAAC,UAAU,CAAC,MAAM,EAAE;gBACtC,IAAI,CAAC,gBAAgB,CAAC,aAAa,CACjC,UAAU,CAAC,UAAU,CAAC,gBAAgB,CAAC,UAAU,CAAC,CACnD,CAAC;aACH;SACF;IACH,CAAC;CACF,CAAA;AAhEC;IADC,IAAA,kBAAM,GAAE;8BACS,6BAAsB;8DAAC;AAGzC;IADC,IAAA,kBAAM,GAAE;8BACS,kCAAsB;8DAAC;AAGzC;IADC,IAAA,kBAAM,GAAE;8BACM,0BAAmB;2DAAC;AAGnC;IADC,IAAA,gBAAI,GAAE;;;;gDAYN;AAtBU,oBAAoB;IAThC,IAAA,yBAAa,EAAC;QACb,SAAS,EAAE,SAAS;QACpB,OAAO,EAAE,CAAC,OAAO,CAAC;QAClB,aAAa,EAAE;YACb;gBACE,OAAO,EAAE,aAAa;aACvB;SACF;KACF,CAAC;GACW,oBAAoB,CAkEhC;AAlEY,oDAAoB","sourcesContent":["import {\n Configuration,\n Init,\n Inject,\n WEB_ROUTER_PARAM_KEY,\n} from '@midwayjs/decorator';\nimport {\n extractExpressLikeValue,\n MidwayConfigService,\n MidwayDecoratorService,\n} from '@midwayjs/core';\nimport * as session from '@midwayjs/express-session';\nimport { MidwayExpressFramework } from './framework';\nimport * as bodyParser from 'body-parser';\nimport * as cookieParser from 'cookie-parser';\nimport * as DefaultConfig from './config/config.default';\n\n@Configuration({\n namespace: 'express',\n imports: [session],\n importConfigs: [\n {\n default: DefaultConfig,\n },\n ],\n})\nexport class ExpressConfiguration {\n @Inject()\n decoratorService: MidwayDecoratorService;\n\n @Inject()\n expressFramework: MidwayExpressFramework;\n\n @Inject()\n configService: MidwayConfigService;\n\n @Init()\n init() {\n this.decoratorService.registerParameterHandler(\n WEB_ROUTER_PARAM_KEY,\n options => {\n return extractExpressLikeValue(\n options.metadata.type,\n options.metadata.propertyData,\n options.originParamType\n )(options.originArgs[0], options.originArgs[1], options.originArgs[2]);\n }\n );\n }\n\n async onReady() {\n const keys =\n this.configService.getConfiguration('express.keys') ??\n this.configService.getConfiguration('keys');\n const cookieParserConfig =\n this.configService.getConfiguration('cookieParser');\n // add cookie parser middleware\n this.expressFramework\n .getMiddleware()\n .insertFirst(\n cookieParser(\n cookieParserConfig.secret ?? keys,\n cookieParserConfig.options\n )\n );\n // add body parser\n const bodyparserConfig = this.configService.getConfiguration('bodyParser');\n if (bodyparserConfig.enable) {\n // create application/json parser\n if (bodyparserConfig.json.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.json(bodyparserConfig.json)\n );\n }\n if (bodyparserConfig.raw.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.raw(bodyparserConfig.raw)\n );\n }\n if (bodyparserConfig.text.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.text(bodyparserConfig.text)\n );\n }\n // create application/x-www-form-urlencoded parser\n if (bodyparserConfig.urlencoded.enable) {\n this.expressFramework.useMiddleware(\n bodyParser.urlencoded(bodyparserConfig.urlencoded)\n );\n }\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"framework.js","sourceRoot":"","sources":["../src/framework.ts"],"names":[],"mappings":";;;;;;;;;AAAA,yCAUwB;AAExB,mDAM6B;AAO7B,mCAAmC;AAEnC,qCAAsD;AACtD,2DAG6B;AAC7B,+BAAgC;AAChC,iCAAkC;AAClC,MAAM,KAAK,GAAG,IAAA,eAAQ,EAAC,cAAc,CAAC,CAAC;AAGvC,IAAa,sBAAsB,GAAnC,MAAa,sBAAuB,SAAQ,oBAM3C;IAKC,SAAS;QACP,OAAO,IAAI,CAAC,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;IACxD,CAAC;IAED,KAAK,CAAC,qBAAqB,CAAC,OAAyC;QACnE,IAAI,CAAC,wBAAwB,GAAG,MAAM,IAAI,CAAC,kBAAkB,CA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1B,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE;YAC3B,IAAI,CAAC,iBAAiB,GAAG,MAAM,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAClE,IAAI,CAAC,iBAAiB,EACtB,IAAI,CAAC,GAAG,CACT,CAAC;YACF,MAAM,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;SACxD;QACD,OAAO,IAAI,CAAC,iBAAiB,CAAC;IAChC,CAAC;IAEM,KAAK,CAAC,UAAU;QACrB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IAEM,SAAS;QACd,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAEM,OAAO;QACZ,OAAO,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IACtC,CAAC;IAEM,gBAAgB;QACrB,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IAEM,4BAA4B;QACjC,OAAO,mCAA0B,CAAC;IACpC,CAAC;CACF,CAAA;AArUY,sBAAsB;IADlC,IAAA,qBAAS,GAAE;GACC,sBAAsB,CAqUlC;AArUY,wDAAsB","sourcesContent":["import {\n BaseFramework,\n HTTP_SERVER_KEY,\n IMidwayBootstrapOptions,\n MiddlewareRespond,\n MidwayFrameworkType,\n PathFileUtil,\n WebRouterCollector,\n RouterInfo,\n httpError,\n} from '@midwayjs/core';\n\nimport {\n Framework,\n WEB_RESPONSE_CONTENT_TYPE,\n WEB_RESPONSE_HEADER,\n WEB_RESPONSE_HTTP_CODE,\n WEB_RESPONSE_REDIRECT,\n} from '@midwayjs/decorator';\nimport {\n IMidwayExpressApplication,\n IMidwayExpressConfigurationOptions,\n Context,\n} from './interface';\nimport type { IRouter, IRouterHandler, Response, NextFunction } from 'express';\nimport * as express from 'express';\nimport { Server } from 'net';\nimport { MidwayExpressContextLogger } from './logger';\nimport {\n wrapAsyncHandler,\n MidwayExpressMiddlewareService,\n} from './middlewareService';\nimport { debuglog } from 'util';\nimport { sendData } from './util';\nconst debug = debuglog('midway:debug');\n\n@Framework()\nexport class MidwayExpressFramework extends BaseFramework<\n IMidwayExpressApplication,\n Context,\n IMidwayExpressConfigurationOptions,\n Response,\n NextFunction\n> {\n public app: IMidwayExpressApplication;\n private server: Server;\n private expressMiddlewareService: MidwayExpressMiddlewareService;\n\n configure(): IMidwayExpressConfigurationOptions {\n return this.configService.getConfiguration('express');\n }\n\n async applicationInitialize(options: Partial<IMidwayBootstrapOptions>) {\n this.expressMiddlewareService = await this.applicationContext.getAsync(\n MidwayExpressMiddlewareService,\n [this.applicationContext]\n );\n debug('[express]: create express app');\n this.app = express() as unknown as IMidwayExpressApplication;\n debug('[express]: use root middleware');\n // use root middleware\n this.app.use((req, res, next) => {\n const ctx = req as Context;\n this.app.createAnonymousContext(ctx);\n (req as any).requestContext = ctx.requestContext;\n ctx.requestContext.registerObject('req', req);\n ctx.requestContext.registerObject('res', res);\n next();\n });\n\n this.defineApplicationProperties();\n\n // hack use method\n (this.app as any).originUse = this.app.use;\n this.app.use = this.app.useMiddleware as any;\n }\n\n public async run(): Promise<void> {\n debug(`[express]: use middlewares = \"${this.getMiddleware().getNames()}\"`);\n // restore use method\n this.app.use = (this.app as any).originUse;\n\n debug('[express]: use user router middleware');\n // load controller,must apply router filter here\n const routerMiddlewares = await this.loadMidwayController();\n\n // use global middleware\n const globalMiddleware = await this.applyMiddleware();\n debug('[express]: use and apply all framework and global middleware');\n this.app.use(globalMiddleware as any);\n\n // load router after global middleware\n for (const info of routerMiddlewares) {\n this.app.use(info.prefix, info.middleware);\n }\n\n debug('[express]: use 404 not found middleware');\n // eslint-disable-next-line\n this.app.use(function notFound(req, res, next) {\n next(new httpError.NotFoundError());\n });\n\n debug('[express]: use global error handler middleware');\n // use global error handler\n this.app.use((err, req, res, next) => {\n this.filterManager\n .runErrorFilter(err, req, res, next)\n .then(data => {\n const { result, error } = data;\n if (error) {\n const status = error.status ?? res.statusCode ?? 500;\n // 5xx\n if (status >= 500) {\n try {\n req.logger.error(err);\n } catch (ex) {\n this.logger.error(err);\n this.logger.error(ex);\n }\n return;\n }\n\n // 4xx\n try {\n req.logger.warn(err);\n } catch (ex) {\n this.logger.warn(err);\n this.logger.error(ex);\n }\n\n res.status(status);\n next(error);\n } else {\n sendData(res, result);\n }\n })\n .catch(err => {\n next(err);\n });\n });\n\n // https config\n if (this.configurationOptions.key && this.configurationOptions.cert) {\n this.configurationOptions.key = PathFileUtil.getFileContentSync(\n this.configurationOptions.key\n );\n this.configurationOptions.cert = PathFileUtil.getFileContentSync(\n this.configurationOptions.cert\n );\n this.configurationOptions.ca = PathFileUtil.getFileContentSync(\n this.configurationOptions.ca\n );\n\n if (this.configurationOptions.http2) {\n this.server = require('http2').createSecureServer(\n this.configurationOptions,\n this.app\n );\n } else {\n this.server = require('https').createServer(\n this.configurationOptions,\n this.app\n );\n }\n } else {\n if (this.configurationOptions.http2) {\n this.server = require('http2').createServer(this.app);\n } else {\n this.server = require('http').createServer(this.app);\n }\n }\n // register httpServer to applicationContext\n this.applicationContext.registerObject(HTTP_SERVER_KEY, this.server);\n\n const customPort =\n process.env.MIDWAY_HTTP_PORT ?? this.configurationOptions.port;\n if (customPort) {\n new Promise<void>(resolve => {\n const args: any[] = [customPort];\n if (this.configurationOptions.hostname) {\n args.push(this.configurationOptions.hostname);\n }\n args.push(() => {\n resolve();\n });\n\n this.server.listen(...args);\n process.env.MIDWAY_HTTP_PORT = String(customPort);\n });\n }\n }\n\n public getFrameworkType(): MidwayFrameworkType {\n return MidwayFrameworkType.WEB_EXPRESS;\n }\n\n /**\n * wrap controller string to middleware function\n */\n protected generateController(routeInfo: RouterInfo): IRouterHandler<any> {\n return wrapAsyncHandler(async (req, res, next) => {\n const controller = await req.requestContext.getAsync(routeInfo.id);\n\n const result = await controller[routeInfo.method].call(\n controller,\n req,\n res,\n next\n );\n\n if (res.headersSent) {\n // return when response send\n return;\n }\n\n if (res.statusCode === 200 && (result === null || result === undefined)) {\n res.status(204);\n }\n // implement response decorator\n if (\n Array.isArray(routeInfo.responseMetadata) &&\n routeInfo.responseMetadata.length\n ) {\n for (const routerRes of routeInfo.responseMetadata) {\n switch (routerRes.type) {\n case WEB_RESPONSE_HTTP_CODE:\n res.status(routerRes.code);\n break;\n case WEB_RESPONSE_HEADER:\n res.set(routerRes.setHeaders);\n break;\n case WEB_RESPONSE_CONTENT_TYPE:\n res.type(routerRes.contentType);\n break;\n case WEB_RESPONSE_REDIRECT:\n res.redirect(routerRes.code, routerRes.url);\n return;\n }\n }\n }\n\n const { result: returnValue, error } =\n await this.filterManager.runResultFilter(result, req, res, next);\n\n if (error) {\n throw error;\n }\n\n sendData(res, returnValue);\n });\n }\n\n public async loadMidwayController(): Promise<\n Array<{\n prefix: string;\n middleware: any;\n }>\n > {\n const collector = new WebRouterCollector('', {\n globalPrefix: this.configurationOptions.globalPrefix,\n });\n const routerTable = await collector.getRouterTable();\n const routerList = await collector.getRoutePriorityList();\n const routerMiddlewares = [];\n\n for (const routerInfo of routerList) {\n // bind controller first\n this.getApplicationContext().bindClass(routerInfo.routerModule);\n\n this.logger.debug(\n `Load Controller \"${routerInfo.controllerId}\", prefix=${routerInfo.prefix}`\n );\n\n // new router\n const newRouter = this.createRouter(routerInfo.routerOptions);\n\n routerInfo.middleware = routerInfo.middleware ?? [];\n // add router middleware\n if (routerInfo.middleware.length) {\n const routerMiddlewareFn = await this.expressMiddlewareService.compose(\n routerInfo.middleware,\n this.app\n );\n newRouter.use(routerMiddlewareFn);\n }\n\n // add route\n const routes = routerTable.get(routerInfo.prefix);\n for (const routeInfo of routes) {\n const routeMiddlewareList = [];\n // routeInfo middleware\n routeInfo.middleware = routeInfo.middleware ?? [];\n if (routeInfo.middleware.length) {\n const routeMiddlewareFn = await this.expressMiddlewareService.compose(\n routeInfo.middleware,\n this.app\n );\n routeMiddlewareList.push(routeMiddlewareFn);\n }\n\n this.logger.debug(\n `Load Router \"${routeInfo.requestMethod.toUpperCase()} ${\n routeInfo.url\n }\"`\n );\n\n // apply controller from request context\n newRouter[routeInfo.requestMethod].call(\n newRouter,\n routeInfo.url,\n ...routeMiddlewareList,\n this.generateController(routeInfo)\n );\n }\n\n routerMiddlewares.push({\n prefix: routerInfo.prefix,\n middleware: newRouter,\n });\n }\n return routerMiddlewares;\n }\n\n /**\n * @param routerOptions\n */\n protected createRouter(routerOptions: { sensitive }): IRouter {\n return express.Router({ caseSensitive: routerOptions.sensitive });\n }\n\n public async applyMiddleware<Response, NextFunction>(): Promise<\n MiddlewareRespond<Context, Response, NextFunction>\n > {\n if (!this.composeMiddleware) {\n this.composeMiddleware = await this.expressMiddlewareService.compose(\n this.middlewareManager,\n this.app\n );\n await this.filterManager.init(this.applicationContext);\n }\n return this.composeMiddleware;\n }\n\n public async beforeStop() {\n this.server.close();\n }\n\n public getServer() {\n return this.server;\n }\n\n public getPort() {\n return process.env.MIDWAY_HTTP_PORT;\n }\n\n public getFrameworkName() {\n return 'midway:express';\n }\n\n public getDefaultContextLoggerClass() {\n return MidwayExpressContextLogger;\n }\n}\n"]}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,yCAAkE;AAAzD,sGAAA,sBAAsB,OAAa;AAC5C,iDAAwE;AAA/D,8GAAA,oBAAoB,OAAiB;AAC9C,sDAAoC;AACpC,2CAAyB","sourcesContent":["export * from './interface';\nexport { MidwayExpressFramework as Framework } from './framework';\nexport { ExpressConfiguration as Configuration } from './configuration';\nexport * from './middlewareService';\nexport * from './logger';\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"interface.js","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":"","sourcesContent":["import {\n CommonMiddlewareUnion,\n ContextMiddlewareManager,\n IConfigurationOptions,\n IMiddleware,\n IMidwayApplication,\n IMidwayContext\n} from '@midwayjs/core';\nimport { Application as ExpressApplication, NextFunction as ExpressNextFunction, Request as ExpressRequest, Response as ExpressResponse } from 'express';\nimport { Options, OptionsJson, OptionsText, OptionsUrlencoded } from 'body-parser';\n\ntype Request = IMidwayContext<ExpressRequest>;\nexport type Response = ExpressResponse;\nexport type NextFunction = ExpressNextFunction;\nexport interface Context extends Request {}\n\n/**\n * @deprecated use Context\n */\nexport type IMidwayExpressRequest = Context;\n/**\n * @deprecated use Context\n */\nexport type IMidwayExpressContext = Context;\nexport type IMidwayExpressMiddleware = IMiddleware<Context, ExpressResponse, ExpressNextFunction>;\nexport interface IMidwayExpressApplication extends IMidwayApplication<Context, ExpressApplication> {\n /**\n * add global middleware to app\n * @param Middleware\n */\n useMiddleware<Response, NextFunction>(Middleware: CommonMiddlewareUnion<Context, Response, NextFunction>): void;\n\n /**\n * get global middleware\n */\n getMiddleware<Response, NextFunction>(): ContextMiddlewareManager<Context, Response, NextFunction>;\n}\n\nexport interface IMidwayExpressConfigurationOptions extends IConfigurationOptions {\n /**\n * session or cookie secret key\n */\n keys?: string | string[];\n /**\n * application http port\n */\n port?: number;\n /**\n * application hostname, 127.0.0.1 as default\n */\n hostname?: string;\n /**\n * https key\n */\n key?: string | Buffer | Array<Buffer | Object>;\n /**\n * https cert\n */\n cert?: string | Buffer | Array<string | Buffer>;\n /**\n * https ca\n */\n ca?: string | Buffer | Array<string | Buffer>;\n /**\n * http2 support\n */\n http2?: boolean;\n /**\n * http global prefix\n */\n globalPrefix?: string;\n}\n\nexport type Application = IMidwayExpressApplication;\n\ndeclare module '@midwayjs/core/dist/interface' {\n interface MidwayConfig {\n express?: IMidwayExpressConfigurationOptions;\n bodyParser?: {\n enable?: boolean;\n json?: OptionsJson & {\n enable?: boolean;\n };\n raw?: Options & {\n enable?: boolean;\n };\n text?: OptionsText & {\n enable?: boolean;\n };\n urlencoded?: OptionsUrlencoded & {\n enable?: boolean;\n };\n }\n }\n}\n"]}
package/dist/logger.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import { MidwayContextLogger } from '@midwayjs/logger';
2
- import { Context } from './interface';
3
- export declare class MidwayExpressContextLogger extends MidwayContextLogger<Context> {
4
- formatContextLabel(): string;
5
- }
6
- //# sourceMappingURL=logger.d.ts.map
package/dist/logger.js DELETED
@@ -1,27 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayExpressContextLogger = void 0;
4
- const logger_1 = require("@midwayjs/logger");
5
- class MidwayExpressContextLogger extends logger_1.MidwayContextLogger {
6
- formatContextLabel() {
7
- var _a;
8
- const req = this.ctx;
9
- // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
10
- const userId = ((_a = req === null || req === void 0 ? void 0 : req['session']) === null || _a === void 0 ? void 0 : _a['userId']) || '-';
11
- const traceId = '-';
12
- const use = Date.now() - this.ctx.startTime;
13
- return (userId +
14
- '/' +
15
- req.ip +
16
- '/' +
17
- traceId +
18
- '/' +
19
- use +
20
- 'ms ' +
21
- req.method +
22
- ' ' +
23
- req.url);
24
- }
25
- }
26
- exports.MidwayExpressContextLogger = MidwayExpressContextLogger;
27
- //# sourceMappingURL=logger.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;AAAA,6CAAuD;AAGvD,MAAa,0BAA2B,SAAQ,4BAA4B;IAC1E,kBAAkB;;QAChB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACrB,wDAAwD;QACxD,MAAM,MAAM,GAAG,CAAA,MAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAG,SAAS,CAAC,0CAAG,QAAQ,CAAC,KAAI,GAAG,CAAC;QACnD,MAAM,OAAO,GAAG,GAAG,CAAC;QACpB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC;QAC5C,OAAO,CACL,MAAM;YACN,GAAG;YACH,GAAG,CAAC,EAAE;YACN,GAAG;YACH,OAAO;YACP,GAAG;YACH,GAAG;YACH,KAAK;YACL,GAAG,CAAC,MAAM;YACV,GAAG;YACH,GAAG,CAAC,GAAG,CACR,CAAC;IACJ,CAAC;CACF;AArBD,gEAqBC","sourcesContent":["import { MidwayContextLogger } from '@midwayjs/logger';\nimport { Context } from './interface';\n\nexport class MidwayExpressContextLogger extends MidwayContextLogger<Context> {\n formatContextLabel() {\n const req = this.ctx;\n // format: '[$userId/$ip/$traceId/$use_ms $method $url]'\n const userId = req?.['session']?.['userId'] || '-';\n const traceId = '-';\n const use = Date.now() - this.ctx.startTime;\n return (\n userId +\n '/' +\n req.ip +\n '/' +\n traceId +\n '/' +\n use +\n 'ms ' +\n req.method +\n ' ' +\n req.url\n );\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"middlewareService.js","sourceRoot":"","sources":["../src/middlewareService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mDAAuE;AACvE,yCAMwB;AAGxB,iCAAkC;AAElC,SAAgB,gBAAgB,CAAC,EAAE;IACjC,IAAI,iBAAK,CAAC,eAAe,CAAC,EAAE,CAAC,EAAE;QAC7B,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YACxB,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;gBACpC,IAAI,CAAC,GAAG,CAAC,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;KACH;SAAM;QACL,OAAO,EAAE,CAAC;KACX;AACH,CAAC;AAVD,4CAUC;AAID,IAAa,8BAA8B,GAA3C,MAAa,8BAA8B;IACzC,YAAqB,kBAAoC;QAApC,uBAAkB,GAAlB,kBAAkB,CAAkB;IAAG,CAAC;IAE7D,KAAK,CAAC,OAAO,CACX,UAEC,EACD,GAAgB,EAChB,IAAa;QAEb,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;YAC9B,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EAAE;oBACZ,0DAA0D;oBAC1D,IAAI,KAAK,GAAG,GAAG;wBAAE,MAAM,GAAG,CAAC;oBAC3B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;iBAClB;YACH,CAAC;YACD,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;QACrB,CAAC,CAAC;QACF,IAAI,IAAI,EAAE;YACR,SAAS,CAAC,KAAK,GAAG,IAAI,CAAC;SACxB;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF,CAAA;AArGY,8BAA8B;IAF1C,IAAA,mBAAO,GAAE;IACT,IAAA,iBAAK,EAAC,qBAAS,CAAC,SAAS,CAAC;;GACd,8BAA8B,CAqG1C;AArGY,wEAA8B;AAuG3C,SAAgB,cAAc,CAAC,EAAqC,EAAE,OAAO;IAC3E,yBAAyB;IACzB,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAE1C,2CAA2C;IAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACjD,MAAM,KAAK,GAAG,IAAA,mBAAY,EAAC,OAAO,CAAC,CAAC;IAEpC,MAAM,EAAE,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;YAAE,OAAO,IAAI,EAAE,CAAC;QAC/B,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC;IACF,EAAE,CAAC,KAAK,GAAI,EAAU,CAAC,KAAK,GAAG,mBAAmB,CAAC;IACnD,OAAO,EAAE,CAAC;AACZ,CAAC;AAdD,wCAcC","sourcesContent":["import { Types, Provide, Scope, ScopeEnum } from '@midwayjs/decorator';\nimport {\n IMidwayContainer,\n MidwayCommonError,\n CommonMiddleware,\n FunctionMiddleware,\n pathMatching,\n} from '@midwayjs/core';\nimport { Context, IMidwayExpressMiddleware, Application } from './interface';\nimport { NextFunction, Response } from 'express';\nimport { sendData } from './util';\n\nexport function wrapAsyncHandler(fn): any {\n if (Types.isAsyncFunction(fn)) {\n return (req, res, next) => {\n return fn(req, res, next).catch(err => {\n next(err);\n });\n };\n } else {\n return fn;\n }\n}\n\n@Provide()\n@Scope(ScopeEnum.Singleton)\nexport class MidwayExpressMiddlewareService {\n constructor(readonly applicationContext: IMidwayContainer) {}\n\n async compose(\n middleware: Array<\n CommonMiddleware<Context, Response, NextFunction> | string\n >,\n app: Application,\n name?: string\n ) {\n if (!Array.isArray(middleware)) {\n throw new MidwayCommonError('Middleware stack must be an array');\n }\n\n const newMiddlewareArr = [];\n\n for (let fn of middleware) {\n if (Types.isClass(fn) || typeof fn === 'string') {\n if (\n typeof fn === 'string' &&\n !this.applicationContext.hasDefinition(fn)\n ) {\n throw new MidwayCommonError(\n 'Middleware definition not found in midway container'\n );\n }\n const classMiddleware =\n await this.applicationContext.getAsync<IMidwayExpressMiddleware>(\n fn as any\n );\n if (classMiddleware) {\n fn = await classMiddleware.resolve(app);\n // wrap async middleware\n fn = wrapAsyncHandler(fn);\n if (!classMiddleware.match && !classMiddleware.ignore) {\n (fn as any)._name = classMiddleware.constructor.name;\n // just got fn\n newMiddlewareArr.push(fn);\n } else {\n // wrap ignore and match\n const mw = fn as any;\n const match = pathMatching({\n match: classMiddleware.match,\n ignore: classMiddleware.ignore,\n });\n fn = (req, res, next) => {\n if (!match(req)) return next();\n return mw(req, res, next);\n };\n (fn as any)._name = classMiddleware.constructor.name;\n newMiddlewareArr.push(fn);\n }\n } else {\n throw new MidwayCommonError('Middleware must have resolve method!');\n }\n } else {\n // wrap async middleware\n fn = wrapAsyncHandler(fn);\n newMiddlewareArr.push(fn);\n }\n }\n\n const composeFn = (\n req: Context,\n res: Response,\n nextFunction: NextFunction\n ) => {\n let index = -1;\n function dispatch(pos: number, err?: Error | null) {\n const handler = newMiddlewareArr[pos];\n index = pos;\n if (err || index === newMiddlewareArr.length) {\n return nextFunction(err);\n }\n\n function next(err?: Error | null) {\n if (pos < index) {\n throw new TypeError('`next()` called multiple times');\n }\n return dispatch(pos + 1, err);\n }\n\n try {\n Promise.resolve(handler(req, res, next)).then(result => {\n if (result) {\n sendData(res, result);\n }\n });\n } catch (err) {\n // Avoid future errors that could diverge stack execution.\n if (index > pos) throw err;\n return next(err);\n }\n }\n return dispatch(0);\n };\n if (name) {\n composeFn._name = name;\n }\n return composeFn;\n }\n}\n\nexport function wrapMiddleware(mw: FunctionMiddleware<any, any, any>, options) {\n // support options.enable\n if (options.enable === false) return null;\n\n // support options.match and options.ignore\n if (!options.match && !options.ignore) return mw;\n const match = pathMatching(options);\n\n const fn = (req, res, next) => {\n if (!match(req)) return next();\n return mw(req, res, next);\n };\n fn._name = (mw as any)._name + 'middlewareWrapper';\n return fn;\n}\n"]}
package/dist/util.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;AAAA,SAAgB,QAAQ,CAAC,GAAG,EAAE,IAAI;IAChC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC;KAC5C;SAAM;QACL,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KACvC;AACH,CAAC;AAND,4BAMC","sourcesContent":["export function sendData(res, data) {\n if (typeof data === 'number') {\n res.status(res.statusCode).send('' + data);\n } else {\n res.status(res.statusCode).send(data);\n }\n}\n"]}