@midwayjs/koa 3.0.0-beta.8 → 3.0.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
@@ -1,6 +1,6 @@
1
1
  # midway for koa
2
2
 
3
- [![Package Quality](http://npm.packagequality.com/shield/midway-web.svg)](http://packagequality.com/#?package=midway-web)
3
+ [![Package Quality](http://npm.packagequality.com/shield/@midwayjs/koa.svg)](http://packagequality.com/#?package=@midwayjs/koa)
4
4
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/midwayjs/midway/pulls)
5
5
 
6
6
  this is a sub package for midway.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * koa server options
3
+ */
4
+ export declare const koa: {};
5
+ /**
6
+ * The key that signing cookies. It can contain multiple keys seperated by `,`.
7
+ * @member {String} Config#keys
8
+ */
9
+ export declare const keys = "";
10
+ /**
11
+ * default cookie options
12
+ *
13
+ * @member Config#cookies
14
+ * @property {String} sameSite - SameSite property, defaults is ''
15
+ * @property {Boolean} httpOnly - httpOnly property, defaults is true
16
+ */
17
+ export declare const cookies: {};
18
+ export declare const onerror: {};
19
+ /**
20
+ * @member Config#bodyParser
21
+ * @property {Boolean} enable - enable bodyParser or not, default is true
22
+ * @property {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set `ignore` when `match` presented
23
+ * @property {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern
24
+ * @property {String} encoding - body's encoding type,default is utf8
25
+ * @property {String} formLimit - limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 1mb
26
+ * @property {String} jsonLimit - limit of the json body, default is 1mb
27
+ * @property {String} textLimit - limit of the text body, default is 1mb
28
+ * @property {Boolean} strict - when set to true, JSON parser will only accept arrays and objects. Default is true
29
+ * @property {Number} queryString.arrayLimit - urlencoded body array's max length, default is 100
30
+ * @property {Number} queryString.depth - urlencoded body object's max depth, default is 5
31
+ * @property {Number} queryString.parameterLimit - urlencoded body maximum parameters, default is 1000
32
+ */
33
+ export declare const bodyParser: {
34
+ enable: boolean;
35
+ encoding: string;
36
+ formLimit: string;
37
+ jsonLimit: string;
38
+ textLimit: string;
39
+ strict: boolean;
40
+ queryString: {
41
+ arrayLimit: number;
42
+ depth: number;
43
+ parameterLimit: number;
44
+ };
45
+ onerror(err: any): never;
46
+ };
47
+ export declare const siteFile: {
48
+ enable: boolean;
49
+ favicon: any;
50
+ };
51
+ //# sourceMappingURL=config.default.d.ts.map
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.siteFile = exports.bodyParser = exports.onerror = exports.cookies = exports.keys = exports.koa = void 0;
4
+ /**
5
+ * koa server options
6
+ */
7
+ exports.koa = {};
8
+ /**
9
+ * The key that signing cookies. It can contain multiple keys seperated by `,`.
10
+ * @member {String} Config#keys
11
+ */
12
+ exports.keys = '';
13
+ /**
14
+ * default cookie options
15
+ *
16
+ * @member Config#cookies
17
+ * @property {String} sameSite - SameSite property, defaults is ''
18
+ * @property {Boolean} httpOnly - httpOnly property, defaults is true
19
+ */
20
+ exports.cookies = {
21
+ // httpOnly: true | false,
22
+ // sameSite: 'none|lax|strict',
23
+ };
24
+ exports.onerror = {};
25
+ /**
26
+ * @member Config#bodyParser
27
+ * @property {Boolean} enable - enable bodyParser or not, default is true
28
+ * @property {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set `ignore` when `match` presented
29
+ * @property {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern
30
+ * @property {String} encoding - body's encoding type,default is utf8
31
+ * @property {String} formLimit - limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 1mb
32
+ * @property {String} jsonLimit - limit of the json body, default is 1mb
33
+ * @property {String} textLimit - limit of the text body, default is 1mb
34
+ * @property {Boolean} strict - when set to true, JSON parser will only accept arrays and objects. Default is true
35
+ * @property {Number} queryString.arrayLimit - urlencoded body array's max length, default is 100
36
+ * @property {Number} queryString.depth - urlencoded body object's max depth, default is 5
37
+ * @property {Number} queryString.parameterLimit - urlencoded body maximum parameters, default is 1000
38
+ */
39
+ exports.bodyParser = {
40
+ enable: true,
41
+ encoding: 'utf8',
42
+ formLimit: '1mb',
43
+ jsonLimit: '1mb',
44
+ textLimit: '1mb',
45
+ strict: true,
46
+ // @see https://github.com/hapijs/qs/blob/master/lib/parse.js#L8 for more options
47
+ queryString: {
48
+ arrayLimit: 100,
49
+ depth: 5,
50
+ parameterLimit: 1000,
51
+ },
52
+ onerror(err) {
53
+ err.message += ', check bodyParser config';
54
+ throw err;
55
+ },
56
+ };
57
+ exports.siteFile = {
58
+ enable: true,
59
+ favicon: undefined,
60
+ };
61
+ //# sourceMappingURL=config.default.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.default.js","sourceRoot":"","sources":["../../src/config/config.default.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,GAAG,GAAG,EAAE,CAAC;AAEtB;;;GAGG;AACU,QAAA,IAAI,GAAG,EAAE,CAAC;AAEvB;;;;;;GAMG;AACU,QAAA,OAAO,GAAG;AACrB,0BAA0B;AAC1B,+BAA+B;CAChC,CAAC;AAEW,QAAA,OAAO,GAAG,EAAE,CAAC;AAE1B;;;;;;;;;;;;;GAaG;AACU,QAAA,UAAU,GAAG;IACxB,MAAM,EAAE,IAAI;IACZ,QAAQ,EAAE,MAAM;IAChB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,KAAK;IAChB,MAAM,EAAE,IAAI;IACZ,iFAAiF;IACjF,WAAW,EAAE;QACX,UAAU,EAAE,GAAG;QACf,KAAK,EAAE,CAAC;QACR,cAAc,EAAE,IAAI;KACrB;IACD,OAAO,CAAC,GAAG;QACT,GAAG,CAAC,OAAO,IAAI,2BAA2B,CAAC;QAC3C,MAAM,GAAG,CAAC;IACZ,CAAC;CACF,CAAC;AAEW,QAAA,QAAQ,GAAG;IACtB,MAAM,EAAE,IAAI;IACZ,OAAO,EAAE,SAAS;CACnB,CAAC","sourcesContent":["/**\n * koa server options\n */\nexport const koa = {};\n\n/**\n * The key that signing cookies. It can contain multiple keys seperated by `,`.\n * @member {String} Config#keys\n */\nexport const keys = '';\n\n/**\n * default cookie options\n *\n * @member Config#cookies\n * @property {String} sameSite - SameSite property, defaults is ''\n * @property {Boolean} httpOnly - httpOnly property, defaults is true\n */\nexport const cookies = {\n // httpOnly: true | false,\n // sameSite: 'none|lax|strict',\n};\n\nexport const onerror = {};\n\n/**\n * @member Config#bodyParser\n * @property {Boolean} enable - enable bodyParser or not, default is true\n * @property {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set `ignore` when `match` presented\n * @property {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern\n * @property {String} encoding - body's encoding type,default is utf8\n * @property {String} formLimit - limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 1mb\n * @property {String} jsonLimit - limit of the json body, default is 1mb\n * @property {String} textLimit - limit of the text body, default is 1mb\n * @property {Boolean} strict - when set to true, JSON parser will only accept arrays and objects. Default is true\n * @property {Number} queryString.arrayLimit - urlencoded body array's max length, default is 100\n * @property {Number} queryString.depth - urlencoded body object's max depth, default is 5\n * @property {Number} queryString.parameterLimit - urlencoded body maximum parameters, default is 1000\n */\nexport const bodyParser = {\n enable: true,\n encoding: 'utf8',\n formLimit: '1mb',\n jsonLimit: '1mb',\n textLimit: '1mb',\n strict: true,\n // @see https://github.com/hapijs/qs/blob/master/lib/parse.js#L8 for more options\n queryString: {\n arrayLimit: 100,\n depth: 5,\n parameterLimit: 1000,\n },\n onerror(err) {\n err.message += ', check bodyParser config';\n throw err;\n },\n};\n\nexport const siteFile = {\n enable: true,\n favicon: undefined,\n};\n"]}
@@ -1,6 +1,9 @@
1
- import { MidwayDecoratorService } from '@midwayjs/core';
1
+ import { MidwayConfigService, MidwayDecoratorService } from '@midwayjs/core';
2
+ import { MidwayKoaFramework } from './framework';
2
3
  export declare class KoaConfiguration {
3
4
  decoratorService: MidwayDecoratorService;
5
+ koaFramework: MidwayKoaFramework;
6
+ configService: MidwayConfigService;
4
7
  init(): void;
5
8
  onReady(): Promise<void>;
6
9
  }
@@ -12,18 +12,34 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.KoaConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const core_1 = require("@midwayjs/core");
15
+ const session = require("@midwayjs/session");
16
+ const framework_1 = require("./framework");
17
+ const DefaultConfig = require("./config/config.default");
18
+ const bodyparser_middleware_1 = require("./middleware/bodyparser.middleware");
19
+ const fav_middleware_1 = require("./middleware/fav.middleware");
15
20
  let KoaConfiguration = class KoaConfiguration {
16
21
  init() {
22
+ // register param decorator
17
23
  this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
18
24
  return (0, core_1.extractKoaLikeValue)(options.metadata.type, options.metadata.propertyData, options.originParamType)(options.originArgs[0], options.originArgs[1]);
19
25
  });
20
26
  }
21
- async onReady() { }
27
+ async onReady() {
28
+ this.koaFramework.useMiddleware([fav_middleware_1.SiteFileMiddleware, bodyparser_middleware_1.BodyParserMiddleware]);
29
+ }
22
30
  };
23
31
  __decorate([
24
32
  (0, decorator_1.Inject)(),
25
33
  __metadata("design:type", core_1.MidwayDecoratorService)
26
34
  ], KoaConfiguration.prototype, "decoratorService", void 0);
35
+ __decorate([
36
+ (0, decorator_1.Inject)(),
37
+ __metadata("design:type", framework_1.MidwayKoaFramework)
38
+ ], KoaConfiguration.prototype, "koaFramework", void 0);
39
+ __decorate([
40
+ (0, decorator_1.Inject)(),
41
+ __metadata("design:type", core_1.MidwayConfigService)
42
+ ], KoaConfiguration.prototype, "configService", void 0);
27
43
  __decorate([
28
44
  (0, decorator_1.Init)(),
29
45
  __metadata("design:type", Function),
@@ -33,14 +49,10 @@ __decorate([
33
49
  KoaConfiguration = __decorate([
34
50
  (0, decorator_1.Configuration)({
35
51
  namespace: 'koa',
52
+ imports: [session],
36
53
  importConfigs: [
37
54
  {
38
- default: {
39
- koa: {
40
- keys: [],
41
- onerror: {},
42
- },
43
- },
55
+ default: DefaultConfig,
44
56
  },
45
57
  ],
46
58
  })
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mDAK6B;AAC7B,yCAIwB;AACxB,6CAA6C;AAC7C,2CAAiD;AACjD,yDAAyD;AACzD,8EAA0E;AAC1E,gEAAiE;AAWjE,IAAa,gBAAgB,GAA7B,MAAa,gBAAgB;IAW3B,IAAI;QACF,2BAA2B;QAC3B,IAAI,CAAC,gBAAgB,CAAC,wBAAwB,CAC5C,gCAAoB,EACpB,OAAO,CAAC,EAAE;YACR,OAAO,IAAA,0BAAmB,EACxB,OAAO,CAAC,QAAQ,CAAC,IAAI,EACrB,OAAO,CAAC,QAAQ,CAAC,YAAY,EAC7B,OAAO,CAAC,eAAe,CACxB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;QAClD,CAAC,CACF,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,OAAO;QACX,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC,mCAAkB,EAAE,4CAAoB,CAAC,CAAC,CAAC;IAC9E,CAAC;CACF,CAAA;AA1BC;IADC,IAAA,kBAAM,GAAE;8BACS,6BAAsB;0DAAC;AAGzC;IADC,IAAA,kBAAM,GAAE;8BACK,8BAAkB;sDAAC;AAGjC;IADC,IAAA,kBAAM,GAAE;8BACM,0BAAmB;uDAAC;AAGnC;IADC,IAAA,gBAAI,GAAE;;;;4CAaN;AAvBU,gBAAgB;IAT5B,IAAA,yBAAa,EAAC;QACb,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,CAAC,OAAO,CAAC;QAClB,aAAa,EAAE;YACb;gBACE,OAAO,EAAE,aAAa;aACvB;SACF;KACF,CAAC;GACW,gBAAgB,CA4B5B;AA5BY,4CAAgB","sourcesContent":["import {\n Configuration,\n Init,\n Inject,\n WEB_ROUTER_PARAM_KEY,\n} from '@midwayjs/decorator';\nimport {\n extractKoaLikeValue,\n MidwayConfigService,\n MidwayDecoratorService,\n} from '@midwayjs/core';\nimport * as session from '@midwayjs/session';\nimport { MidwayKoaFramework } from './framework';\nimport * as DefaultConfig from './config/config.default';\nimport { BodyParserMiddleware } from './middleware/bodyparser.middleware';\nimport { SiteFileMiddleware } from './middleware/fav.middleware';\n\n@Configuration({\n namespace: 'koa',\n imports: [session],\n importConfigs: [\n {\n default: DefaultConfig,\n },\n ],\n})\nexport class KoaConfiguration {\n @Inject()\n decoratorService: MidwayDecoratorService;\n\n @Inject()\n koaFramework: MidwayKoaFramework;\n\n @Inject()\n configService: MidwayConfigService;\n\n @Init()\n init() {\n // register param decorator\n this.decoratorService.registerParameterHandler(\n WEB_ROUTER_PARAM_KEY,\n options => {\n return extractKoaLikeValue(\n options.metadata.type,\n options.metadata.propertyData,\n options.originParamType\n )(options.originArgs[0], options.originArgs[1]);\n }\n );\n }\n\n async onReady() {\n this.koaFramework.useMiddleware([SiteFileMiddleware, BodyParserMiddleware]);\n }\n}\n"]}
@@ -17,12 +17,13 @@ export declare class MidwayKoaFramework extends BaseFramework<IMidwayKoaApplicat
17
17
  * @deprecated
18
18
  * @param middlewareId
19
19
  */
20
- generateMiddleware(middlewareId: string): Promise<Middleware<DefaultState, IMidwayKoaContext, any>>;
20
+ generateMiddleware(middlewareId: any): Promise<Middleware<DefaultState, IMidwayKoaContext, any>>;
21
21
  run(): Promise<void>;
22
22
  beforeStop(): Promise<void>;
23
23
  getFrameworkType(): MidwayFrameworkType;
24
24
  getFrameworkName(): string;
25
25
  getServer(): Server;
26
+ getPort(): string;
26
27
  useMiddleware(Middleware: CommonMiddlewareUnion<IMidwayKoaContext, Next, unknown>): void;
27
28
  useFilter(Filter: CommonFilterUnion<IMidwayKoaContext, Next, unknown>): void;
28
29
  }
package/dist/framework.js CHANGED
@@ -8,16 +8,16 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.MidwayKoaFramework = void 0;
10
10
  const core_1 = require("@midwayjs/core");
11
+ const cookies_1 = require("@midwayjs/cookies");
11
12
  const decorator_1 = require("@midwayjs/decorator");
12
13
  const Router = require("@koa/router");
13
14
  const koa = require("koa");
14
- const onerror = require("koa-onerror");
15
+ const onerror_1 = require("./onerror");
16
+ const COOKIES = Symbol('context#cookies');
15
17
  class KoaControllerGenerator extends core_1.WebControllerGenerator {
16
- constructor(app, applicationContext, logger) {
17
- super(applicationContext, core_1.MidwayFrameworkType.WEB_KOA, logger);
18
+ constructor(app) {
19
+ super(app);
18
20
  this.app = app;
19
- this.applicationContext = applicationContext;
20
- this.logger = logger;
21
21
  }
22
22
  createRouter(routerOptions) {
23
23
  const router = new Router(routerOptions);
@@ -33,22 +33,40 @@ let MidwayKoaFramework = class MidwayKoaFramework extends core_1.BaseFramework {
33
33
  return this.configService.getConfiguration('koa');
34
34
  }
35
35
  async applicationInitialize(options) {
36
- this.app = new koa();
37
- const appKeys = this.configurationOptions['keys'] ||
38
- this.configService.getConfiguration('keys');
39
- if (appKeys) {
40
- this.app.keys = appKeys;
36
+ const appKeys = this.configService.getConfiguration('keys') ||
37
+ this.configurationOptions['keys'];
38
+ if (!appKeys) {
39
+ throw new core_1.MidwayConfigMissingError('config.keys');
41
40
  }
42
- else {
43
- throw new core_1.MidwayConfigMissingError('koa.keys');
44
- }
45
- onerror(this.app, this.configurationOptions.onerror);
41
+ const cookieOptions = this.configService.getConfiguration('cookies');
42
+ this.app = new koa({
43
+ keys: [].concat(appKeys),
44
+ });
45
+ Object.defineProperty(this.app.context, 'cookies', {
46
+ get() {
47
+ if (!this[COOKIES]) {
48
+ this[COOKIES] = new cookies_1.Cookies(this, this.app.keys, cookieOptions);
49
+ }
50
+ return this[COOKIES];
51
+ },
52
+ enumerable: true,
53
+ });
54
+ const onerrorConfig = this.configService.getConfiguration('onerror');
55
+ (0, onerror_1.setupOnerror)(this.app, onerrorConfig, this.logger);
56
+ // not found middleware
57
+ const notFound = async (ctx, next) => {
58
+ await next();
59
+ if (!ctx._matchedRoute) {
60
+ throw new core_1.httpError.NotFoundError();
61
+ }
62
+ };
63
+ // root middleware
46
64
  const midwayRootMiddleware = async (ctx, next) => {
47
65
  this.app.createAnonymousContext(ctx);
48
- await (await this.getMiddleware())(ctx, next);
66
+ await (await this.applyMiddleware(notFound))(ctx, next);
49
67
  };
50
68
  this.app.use(midwayRootMiddleware);
51
- this.generator = new KoaControllerGenerator(this.app, this.applicationContext, this.appLogger);
69
+ this.generator = new KoaControllerGenerator(this.app);
52
70
  this.defineApplicationProperties();
53
71
  // hack use method
54
72
  this.app.originUse = this.app.use;
@@ -108,7 +126,7 @@ let MidwayKoaFramework = class MidwayKoaFramework extends core_1.BaseFramework {
108
126
  const customPort = (_a = process.env.MIDWAY_HTTP_PORT) !== null && _a !== void 0 ? _a : this.configurationOptions.port;
109
127
  if (customPort) {
110
128
  new Promise(resolve => {
111
- const args = [this.configurationOptions.port];
129
+ const args = [customPort];
112
130
  if (this.configurationOptions.hostname) {
113
131
  args.push(this.configurationOptions.hostname);
114
132
  }
@@ -132,6 +150,9 @@ let MidwayKoaFramework = class MidwayKoaFramework extends core_1.BaseFramework {
132
150
  getServer() {
133
151
  return this.server;
134
152
  }
153
+ getPort() {
154
+ return process.env.MIDWAY_HTTP_PORT;
155
+ }
135
156
  useMiddleware(Middleware) {
136
157
  this.middlewareManager.insertLast(Middleware);
137
158
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"framework.js","sourceRoot":"","sources":["../src/framework.ts"],"names":[],"mappings":";;;;;;;;;AAAA,yCAYwB;AACxB,+CAA4C;AAE5C,mDAAgD;AAOhD,sCAAsC;AAEtC,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,oBAAoB,CAAC,QAAQ,EAAE;oBACtC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC,QAAQ,CAAC,CAAC;iBAC/C;gBACD,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;oBACb,OAAO,EAAE,CAAC;gBACZ,CAAC,CAAC,CAAC;gBACH,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;gBAC5B,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;YACpD,CAAC,CAAC,CAAC;SACJ;IACH,CAAC;IAEM,KAAK,CAAC,UAAU;QACrB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IAEM,gBAAgB;QACrB,OAAO,0BAAmB,CAAC,OAAO,CAAC;IACrC,CAAC;IAEM,gBAAgB;QACrB,OAAO,SAAS,CAAC;IACnB,CAAC;IAEM,SAAS;QACd,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAEM,OAAO;QACZ,OAAO,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IACtC,CAAC;IAEM,aAAa,CAClB,UAAmE;QAEnE,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;IAChD,CAAC;IAEM,SAAS,CACd,MAA2D;QAE3D,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;CACF,CAAA;AA3LY,kBAAkB;IAD9B,IAAA,qBAAS,GAAE;GACC,kBAAkB,CA2L9B;AA3LY,gDAAkB","sourcesContent":["import {\n BaseFramework,\n CommonFilterUnion,\n CommonMiddlewareUnion,\n HTTP_SERVER_KEY,\n IMidwayBootstrapOptions,\n MidwayFrameworkType,\n PathFileUtil,\n RouterInfo,\n WebControllerGenerator,\n MidwayConfigMissingError,\n httpError,\n} from '@midwayjs/core';\nimport { Cookies } from '@midwayjs/cookies';\n\nimport { Framework } from '@midwayjs/decorator';\nimport {\n IMidwayKoaApplication,\n IMidwayKoaConfigurationOptions,\n IMidwayKoaContext,\n IWebMiddleware,\n} from './interface';\nimport * as Router from '@koa/router';\nimport type { DefaultState, Middleware, Next } from 'koa';\nimport * as koa from 'koa';\nimport { Server } from 'net';\nimport { setupOnerror } from './onerror';\n\nconst COOKIES = Symbol('context#cookies');\n\nclass KoaControllerGenerator extends WebControllerGenerator<Router> {\n constructor(readonly app) {\n super(app);\n }\n\n createRouter(routerOptions: any): Router {\n const router = new Router(routerOptions);\n router.prefix(routerOptions.prefix);\n return router;\n }\n\n generateController(routeInfo: RouterInfo) {\n return this.generateKoaController(routeInfo);\n }\n}\n\n@Framework()\nexport class MidwayKoaFramework extends BaseFramework<\n IMidwayKoaApplication,\n IMidwayKoaContext,\n IMidwayKoaConfigurationOptions,\n Next\n> {\n private server: Server;\n private generator: KoaControllerGenerator;\n\n configure(): IMidwayKoaConfigurationOptions {\n return this.configService.getConfiguration('koa');\n }\n\n async applicationInitialize(options: Partial<IMidwayBootstrapOptions>) {\n const appKeys =\n this.configService.getConfiguration('keys') ||\n this.configurationOptions['keys'];\n if (!appKeys) {\n throw new MidwayConfigMissingError('config.keys');\n }\n\n const cookieOptions = this.configService.getConfiguration('cookies');\n\n this.app = new koa<DefaultState, IMidwayKoaContext>({\n keys: [].concat(appKeys),\n }) as IMidwayKoaApplication;\n\n Object.defineProperty(this.app.context, 'cookies', {\n get() {\n if (!this[COOKIES]) {\n this[COOKIES] = new Cookies(this, this.app.keys, cookieOptions);\n }\n return this[COOKIES];\n },\n enumerable: true,\n });\n\n const onerrorConfig = this.configService.getConfiguration('onerror');\n setupOnerror(this.app, onerrorConfig, this.logger);\n\n // not found middleware\n const notFound = async (ctx, next) => {\n await next();\n if (!ctx._matchedRoute) {\n throw new httpError.NotFoundError();\n }\n };\n\n // root middleware\n const midwayRootMiddleware = async (ctx, next) => {\n this.app.createAnonymousContext(ctx);\n await (\n await this.applyMiddleware(notFound)\n )(ctx, next);\n };\n this.app.use(midwayRootMiddleware);\n\n this.generator = new KoaControllerGenerator(this.app);\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 async loadMidwayController() {\n await this.generator.loadMidwayController(\n this.configurationOptions.globalPrefix,\n newRouter => {\n const dispatchFn = newRouter.middleware();\n dispatchFn._name = `midwayController(${\n newRouter?.opts?.prefix || '/'\n })`;\n this.app.use(dispatchFn);\n }\n );\n }\n\n /**\n * wrap controller string to middleware function\n */\n public generateController(\n routeInfo: RouterInfo\n ): Middleware<DefaultState, IMidwayKoaContext> {\n return this.generator.generateKoaController(routeInfo);\n }\n\n /**\n * @deprecated\n * @param middlewareId\n */\n public async generateMiddleware(middlewareId: any) {\n const mwIns = await this.getApplicationContext().getAsync<IWebMiddleware>(\n middlewareId\n );\n return mwIns.resolve();\n }\n\n public async run(): Promise<void> {\n // load controller\n await this.loadMidwayController();\n // restore use method\n this.app.use = (this.app as any).originUse;\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.callback()\n );\n } else {\n this.server = require('https').createServer(\n this.configurationOptions,\n this.app.callback()\n );\n }\n } else {\n if (this.configurationOptions.http2) {\n this.server = require('http2').createServer(this.app.callback());\n } else {\n this.server = require('http').createServer(this.app.callback());\n }\n }\n // register httpServer to applicationContext\n this.applicationContext.registerObject(HTTP_SERVER_KEY, this.server);\n\n // set port and listen server\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 this.server.listen(...args);\n process.env.MIDWAY_HTTP_PORT = String(customPort);\n });\n }\n }\n\n public async beforeStop() {\n this.server.close();\n }\n\n public getFrameworkType(): MidwayFrameworkType {\n return MidwayFrameworkType.WEB_KOA;\n }\n\n public getFrameworkName() {\n return 'web:koa';\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 useMiddleware(\n Middleware: CommonMiddlewareUnion<IMidwayKoaContext, Next, unknown>\n ) {\n this.middlewareManager.insertLast(Middleware);\n }\n\n public useFilter(\n Filter: CommonFilterUnion<IMidwayKoaContext, Next, unknown>\n ) {\n this.filterManager.useFilter(Filter);\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -2,4 +2,6 @@ export { MidwayKoaFramework as Framework } from './framework';
2
2
  export { MidwayKoaContextLogger } from './logger';
3
3
  export * from './interface';
4
4
  export { KoaConfiguration as Configuration } from './configuration';
5
+ export * from './middleware/fav.middleware';
6
+ export * from './middleware/bodyparser.middleware';
5
7
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -18,4 +18,6 @@ Object.defineProperty(exports, "MidwayKoaContextLogger", { enumerable: true, get
18
18
  __exportStar(require("./interface"), exports);
19
19
  var configuration_1 = require("./configuration");
20
20
  Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.KoaConfiguration; } });
21
+ __exportStar(require("./middleware/fav.middleware"), exports);
22
+ __exportStar(require("./middleware/bodyparser.middleware"), exports);
21
23
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,yCAA8D;AAArD,sGAAA,kBAAkB,OAAa;AACxC,mCAAkD;AAAzC,gHAAA,sBAAsB,OAAA;AAC/B,8CAA4B;AAC5B,iDAAoE;AAA3D,8GAAA,gBAAgB,OAAiB;AAC1C,8DAA4C;AAC5C,qEAAmD","sourcesContent":["export { MidwayKoaFramework as Framework } from './framework';\nexport { MidwayKoaContextLogger } from './logger';\nexport * from './interface';\nexport { KoaConfiguration as Configuration } from './configuration';\nexport * from './middleware/fav.middleware';\nexport * from './middleware/bodyparser.middleware';\n"]}
@@ -3,6 +3,7 @@ import { IConfigurationOptions, IMidwayApplication, IMidwayContext } from '@midw
3
3
  import * as koa from 'koa';
4
4
  import { Context as KoaContext, DefaultState, Middleware, Next } from 'koa';
5
5
  import { RouterParamValue } from '@midwayjs/decorator';
6
+ import { CookieSetOptions } from '@midwayjs/cookies';
6
7
  export declare type IMidwayKoaContext = IMidwayContext<KoaContext>;
7
8
  export declare type IMidwayKoaApplication = IMidwayApplication<IMidwayKoaContext, koa<DefaultState, IMidwayKoaContext> & {
8
9
  generateController(controllerMapping: string, routeArgsInfo?: RouterParamValue[], routerResponseData?: any[]): Middleware<DefaultState, IMidwayKoaContext>;
@@ -10,11 +11,18 @@ export declare type IMidwayKoaApplication = IMidwayApplication<IMidwayKoaContext
10
11
  * @deprecated
11
12
  * @param middlewareId
12
13
  */
13
- generateMiddleware(middlewareId: string): Promise<Middleware<DefaultState, IMidwayKoaContext>>;
14
+ generateMiddleware(middlewareId: any): Promise<Middleware<DefaultState, IMidwayKoaContext>>;
14
15
  }>;
16
+ /**
17
+ * @deprecated use NextFunction definition
18
+ */
15
19
  export declare type IMidwayKoaNext = Next;
16
20
  export declare type NextFunction = Next;
17
21
  export interface IMidwayKoaConfigurationOptions extends IConfigurationOptions {
22
+ /**
23
+ * cookies sign keys
24
+ */
25
+ keys?: string[];
18
26
  /**
19
27
  * application http port
20
28
  */
@@ -43,17 +51,6 @@ export interface IMidwayKoaConfigurationOptions extends IConfigurationOptions {
43
51
  * http global prefix
44
52
  */
45
53
  globalPrefix?: string;
46
- /**
47
- * onerror middleware options
48
- */
49
- onerror?: {
50
- text: (err: Error, ctx: IMidwayKoaContext) => void;
51
- json: (err: Error, ctx: IMidwayKoaContext) => void;
52
- html: (err: Error, ctx: IMidwayKoaContext) => void;
53
- redirect?: string;
54
- template?: string;
55
- accepts?: (...args: any[]) => any;
56
- };
57
54
  }
58
55
  export declare type MiddlewareParamArray = Array<Middleware<DefaultState, IMidwayKoaContext>>;
59
56
  export interface IWebMiddleware {
@@ -62,9 +59,81 @@ export interface IWebMiddleware {
62
59
  export declare type Application = IMidwayKoaApplication;
63
60
  export interface Context extends IMidwayKoaContext {
64
61
  }
62
+ interface BodyParserOptions {
63
+ enable?: boolean;
64
+ /**
65
+ * parser will only parse when request type hits enableTypes, default is ['json', 'form'].
66
+ */
67
+ enableTypes?: string[];
68
+ /**
69
+ * requested encoding. Default is utf-8 by co-body
70
+ */
71
+ encode?: string;
72
+ /**
73
+ * limit of the urlencoded body. If the body ends up being larger than this limit
74
+ * a 413 error code is returned. Default is 56kb
75
+ */
76
+ formLimit?: string;
77
+ /**
78
+ * limit of the json body. Default is 1mb
79
+ */
80
+ jsonLimit?: string;
81
+ /**
82
+ * limit of the text body. Default is 1mb.
83
+ */
84
+ textLimit?: string;
85
+ /**
86
+ * limit of the xml body. Default is 1mb.
87
+ */
88
+ xmlLimit?: string;
89
+ /**
90
+ * when set to true, JSON parser will only accept arrays and objects. Default is true
91
+ */
92
+ strict?: boolean;
93
+ /**
94
+ * custom json request detect function. Default is null
95
+ */
96
+ detectJSON?: ((ctx: IMidwayKoaContext) => boolean);
97
+ /**
98
+ * support extend types
99
+ */
100
+ extendTypes?: {
101
+ json?: string[];
102
+ form?: string[];
103
+ text?: string[];
104
+ };
105
+ /**
106
+ * support custom error handle
107
+ */
108
+ onerror?: ((err: Error, ctx: IMidwayKoaContext) => void);
109
+ }
65
110
  declare module '@midwayjs/core/dist/interface' {
66
111
  interface MidwayConfig {
112
+ keys?: string | string[];
67
113
  koa?: IMidwayKoaConfigurationOptions;
114
+ cookies?: CookieSetOptions;
115
+ /**
116
+ * onerror middleware options
117
+ */
118
+ onerror?: {
119
+ text?: (err: Error, ctx: IMidwayKoaContext) => void;
120
+ json?: (err: Error, ctx: IMidwayKoaContext) => void;
121
+ html?: (err: Error, ctx: IMidwayKoaContext) => void;
122
+ redirect?: string;
123
+ accepts?: (...args: any[]) => any;
124
+ };
125
+ bodyParser?: BodyParserOptions;
126
+ siteFile?: {
127
+ enable?: boolean;
128
+ favicon?: undefined | string | Buffer;
129
+ };
130
+ }
131
+ }
132
+ declare module 'koa' {
133
+ interface Request {
134
+ body?: any;
135
+ rawBody: string;
68
136
  }
69
137
  }
138
+ export {};
70
139
  //# sourceMappingURL=interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interface.js","sourceRoot":"","sources":["../src/interface.ts"],"names":[],"mappings":"","sourcesContent":["import { IConfigurationOptions, IMidwayApplication, IMidwayContext } from '@midwayjs/core';\nimport * as koa from 'koa';\nimport { Context as KoaContext, DefaultState, Middleware, Next } from 'koa';\nimport { RouterParamValue } from '@midwayjs/decorator';\nimport { CookieSetOptions } from '@midwayjs/cookies';\n\nexport type IMidwayKoaContext = IMidwayContext<KoaContext>;\nexport type IMidwayKoaApplication = IMidwayApplication<IMidwayKoaContext, koa<DefaultState, IMidwayKoaContext> & {\n generateController(\n controllerMapping: string,\n routeArgsInfo?: RouterParamValue[],\n routerResponseData?: any []\n ): Middleware<DefaultState, IMidwayKoaContext>;\n /**\n * @deprecated\n * @param middlewareId\n */\n generateMiddleware(middlewareId: any): Promise<Middleware<DefaultState, IMidwayKoaContext>>;\n}>;\n\n/**\n * @deprecated use NextFunction definition\n */\nexport type IMidwayKoaNext = Next;\nexport type NextFunction = Next;\n\nexport interface IMidwayKoaConfigurationOptions extends IConfigurationOptions {\n /**\n * cookies sign keys\n */\n keys?: 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 MiddlewareParamArray = Array<Middleware<DefaultState, IMidwayKoaContext>>;\n\nexport interface IWebMiddleware {\n resolve(): koa.Middleware<DefaultState, IMidwayKoaContext>;\n}\n\nexport type Application = IMidwayKoaApplication;\n\nexport interface Context extends IMidwayKoaContext {}\n\ninterface BodyParserOptions {\n enable?: boolean;\n /**\n * parser will only parse when request type hits enableTypes, default is ['json', 'form'].\n */\n enableTypes?: string[];\n\n /**\n * requested encoding. Default is utf-8 by co-body\n */\n encode?: string;\n\n /**\n * limit of the urlencoded body. If the body ends up being larger than this limit\n * a 413 error code is returned. Default is 56kb\n */\n formLimit?: string;\n\n /**\n * limit of the json body. Default is 1mb\n */\n jsonLimit?: string;\n\n /**\n * limit of the text body. Default is 1mb.\n */\n textLimit?: string;\n\n /**\n * limit of the xml body. Default is 1mb.\n */\n xmlLimit?: string;\n\n /**\n * when set to true, JSON parser will only accept arrays and objects. Default is true\n */\n strict?: boolean;\n\n /**\n * custom json request detect function. Default is null\n */\n detectJSON?: ((ctx: IMidwayKoaContext) => boolean);\n\n /**\n * support extend types\n */\n extendTypes?: {\n json?: string[];\n form?: string[];\n text?: string[];\n };\n\n /**\n * support custom error handle\n */\n onerror?: ((err: Error, ctx: IMidwayKoaContext) => void);\n}\n\ndeclare module '@midwayjs/core/dist/interface' {\n interface MidwayConfig {\n keys?: string | string[];\n koa?: IMidwayKoaConfigurationOptions;\n cookies?: CookieSetOptions;\n /**\n * onerror middleware options\n */\n onerror?: {\n text?: (err: Error, ctx: IMidwayKoaContext) => void;\n json?: (err: Error, ctx: IMidwayKoaContext) => void;\n html?: (err: Error, ctx: IMidwayKoaContext) => void;\n redirect?: string;\n accepts?: (...args) => any;\n },\n bodyParser?: BodyParserOptions;\n siteFile?: {\n enable?: boolean;\n favicon?: undefined | string | Buffer\n };\n }\n}\n\ndeclare module 'koa' {\n interface Request {\n body?: any;\n rawBody: string;\n }\n}\n\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;AAAA,6CAAuD;AAGvD,MAAa,sBAAuB,SAAQ,4BAAsC;IAChF,kBAAkB;QAChB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACrB,wDAAwD;QACxD,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC;QACjC,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC;QAC1D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,SAAS,CAAC;QACvC,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,wDAqBC","sourcesContent":["import { MidwayContextLogger } from '@midwayjs/logger';\nimport { IMidwayKoaContext } from './interface';\n\nexport class MidwayKoaContextLogger extends MidwayContextLogger<IMidwayKoaContext> {\n formatContextLabel() {\n const ctx = this.ctx;\n // format: '[$userId/$ip/$traceId/$use_ms $method $url]'\n const userId = ctx.userId || '-';\n const traceId = (ctx.tracer && ctx.tracer.traceId) || '-';\n const use = Date.now() - ctx.startTime;\n return (\n userId +\n '/' +\n ctx.ip +\n '/' +\n traceId +\n '/' +\n use +\n 'ms ' +\n ctx.method +\n ' ' +\n ctx.url\n );\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export declare class BodyParserMiddleware {
2
+ bodyparserConfig: any;
3
+ resolve(): any;
4
+ static getName(): string;
5
+ }
6
+ //# sourceMappingURL=bodyparser.middleware.d.ts.map
@@ -0,0 +1,34 @@
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.BodyParserMiddleware = void 0;
13
+ const koaBodyParser = require("koa-bodyparser");
14
+ const decorator_1 = require("@midwayjs/decorator");
15
+ let BodyParserMiddleware = class BodyParserMiddleware {
16
+ resolve() {
17
+ // use bodyparser middleware
18
+ if (this.bodyparserConfig.enable) {
19
+ return koaBodyParser(this.bodyparserConfig);
20
+ }
21
+ }
22
+ static getName() {
23
+ return 'bodyParser';
24
+ }
25
+ };
26
+ __decorate([
27
+ (0, decorator_1.Config)('bodyParser'),
28
+ __metadata("design:type", Object)
29
+ ], BodyParserMiddleware.prototype, "bodyparserConfig", void 0);
30
+ BodyParserMiddleware = __decorate([
31
+ (0, decorator_1.Middleware)()
32
+ ], BodyParserMiddleware);
33
+ exports.BodyParserMiddleware = BodyParserMiddleware;
34
+ //# sourceMappingURL=bodyparser.middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bodyparser.middleware.js","sourceRoot":"","sources":["../../src/middleware/bodyparser.middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,gDAAgD;AAChD,mDAAyD;AAGzD,IAAa,oBAAoB,GAAjC,MAAa,oBAAoB;IAI/B,OAAO;QACL,4BAA4B;QAC5B,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE;YAChC,OAAO,aAAa,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;SAC7C;IACH,CAAC;IAED,MAAM,CAAC,OAAO;QACZ,OAAO,YAAY,CAAC;IACtB,CAAC;CACF,CAAA;AAZC;IADC,IAAA,kBAAM,EAAC,YAAY,CAAC;;8DACJ;AAFN,oBAAoB;IADhC,IAAA,sBAAU,GAAE;GACA,oBAAoB,CAchC;AAdY,oDAAoB","sourcesContent":["import * as koaBodyParser from 'koa-bodyparser';\nimport { Config, Middleware } from '@midwayjs/decorator';\n\n@Middleware()\nexport class BodyParserMiddleware {\n @Config('bodyParser')\n bodyparserConfig;\n\n resolve() {\n // use bodyparser middleware\n if (this.bodyparserConfig.enable) {\n return koaBodyParser(this.bodyparserConfig);\n }\n }\n\n static getName() {\n return 'bodyParser';\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export declare class SiteFileMiddleware {
2
+ siteFileConfig: any;
3
+ resolve(): (ctx: any, next: any) => Promise<any>;
4
+ static getName(): string;
5
+ }
6
+ //# sourceMappingURL=fav.middleware.d.ts.map
@@ -0,0 +1,62 @@
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.SiteFileMiddleware = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ const path = require('path');
15
+ const MAX_AGE = 'public, max-age=2592000'; // 30 days
16
+ let SiteFileMiddleware = class SiteFileMiddleware {
17
+ resolve() {
18
+ // use bodyparser middleware
19
+ if (this.siteFileConfig.enable) {
20
+ return async (ctx, next) => {
21
+ if (ctx.method !== 'HEAD' && ctx.method !== 'GET')
22
+ return next();
23
+ /* istanbul ignore if */
24
+ if (ctx.path[0] !== '/')
25
+ return next();
26
+ if (ctx.path !== '/favicon.ico') {
27
+ return next();
28
+ }
29
+ let content = this.siteFileConfig['favicon'];
30
+ if (content === undefined) {
31
+ content = Buffer.from('');
32
+ }
33
+ if (!content)
34
+ return next();
35
+ // content is url
36
+ if (typeof content === 'string')
37
+ return ctx.redirect(content);
38
+ // '/robots.txt': Buffer <xx..
39
+ // content is buffer
40
+ if (Buffer.isBuffer(content)) {
41
+ ctx.set('cache-control', MAX_AGE);
42
+ ctx.body = content;
43
+ ctx.type = path.extname(ctx.path);
44
+ return;
45
+ }
46
+ return next();
47
+ };
48
+ }
49
+ }
50
+ static getName() {
51
+ return 'siteFile';
52
+ }
53
+ };
54
+ __decorate([
55
+ (0, decorator_1.Config)('siteFile'),
56
+ __metadata("design:type", Object)
57
+ ], SiteFileMiddleware.prototype, "siteFileConfig", void 0);
58
+ SiteFileMiddleware = __decorate([
59
+ (0, decorator_1.Middleware)()
60
+ ], SiteFileMiddleware);
61
+ exports.SiteFileMiddleware = SiteFileMiddleware;
62
+ //# sourceMappingURL=fav.middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fav.middleware.js","sourceRoot":"","sources":["../../src/middleware/fav.middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mDAAyD;AAEzD,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAC7B,MAAM,OAAO,GAAG,yBAAyB,CAAC,CAAC,UAAU;AAGrD,IAAa,k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;CACF,CAAA;AAvCC;IADC,IAAA,kBAAM,EAAC,UAAU,CAAC;;0DACJ;AAFJ,kBAAkB;IAD9B,IAAA,sBAAU,GAAE;GACA,kBAAkB,CAyC9B;AAzCY,gDAAkB","sourcesContent":["import { Config, Middleware } from '@midwayjs/decorator';\n\nconst path = require('path');\nconst MAX_AGE = 'public, max-age=2592000'; // 30 days\n\n@Middleware()\nexport class SiteFileMiddleware {\n @Config('siteFile')\n siteFileConfig;\n\n resolve() {\n // use bodyparser middleware\n if (this.siteFileConfig.enable) {\n return async (ctx, next) => {\n if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return next();\n /* istanbul ignore if */\n if (ctx.path[0] !== '/') return next();\n\n if (ctx.path !== '/favicon.ico') {\n return next();\n }\n\n let content = this.siteFileConfig['favicon'];\n if (content === undefined) {\n content = Buffer.from('');\n }\n if (!content) return next();\n // content is url\n if (typeof content === 'string') return ctx.redirect(content);\n\n // '/robots.txt': Buffer <xx..\n // content is buffer\n if (Buffer.isBuffer(content)) {\n ctx.set('cache-control', MAX_AGE);\n ctx.body = content;\n ctx.type = path.extname(ctx.path);\n return;\n }\n\n return next();\n };\n }\n }\n\n static getName() {\n return 'siteFile';\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function setupOnerror(app: any, config: any, logger: any): void;
2
+ //# sourceMappingURL=onerror.d.ts.map