@midwayjs/core 3.0.0-beta.3 → 3.0.0-beta.7

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/baseFramework.d.ts +11 -9
  3. package/dist/baseFramework.js +21 -15
  4. package/dist/{util → common}/fileDetector.d.ts +0 -0
  5. package/dist/{util → common}/fileDetector.js +0 -0
  6. package/dist/common/filterManager.d.ts +19 -0
  7. package/dist/common/filterManager.js +85 -0
  8. package/dist/common/middlewareManager.d.ts +11 -0
  9. package/dist/{util → common}/middlewareManager.js +0 -0
  10. package/dist/{util → common}/serviceFactory.d.ts +0 -0
  11. package/dist/{util → common}/serviceFactory.js +0 -0
  12. package/dist/{util → common}/triggerCollector.d.ts +0 -0
  13. package/dist/{util → common}/triggerCollector.js +0 -0
  14. package/dist/{util → common}/webGenerator.d.ts +6 -9
  15. package/dist/{util → common}/webGenerator.js +14 -21
  16. package/dist/{util → common}/webRouterCollector.d.ts +9 -4
  17. package/dist/{util → common}/webRouterCollector.js +47 -27
  18. package/dist/error/base.d.ts +3 -1
  19. package/dist/error/base.js +1 -0
  20. package/dist/error/code.d.ts +2 -1
  21. package/dist/error/code.js +2 -1
  22. package/dist/error/framework.d.ts +5 -2
  23. package/dist/error/framework.js +14 -5
  24. package/dist/error/http.d.ts +2 -1
  25. package/dist/error/http.js +3 -3
  26. package/dist/error/index.d.ts +1 -0
  27. package/dist/error/index.js +1 -0
  28. package/dist/index.d.ts +8 -9
  29. package/dist/index.js +9 -11
  30. package/dist/interface.d.ts +32 -29
  31. package/dist/service/decoratorService.js +23 -21
  32. package/dist/service/frameworkService.d.ts +4 -3
  33. package/dist/service/frameworkService.js +10 -0
  34. package/dist/service/lifeCycleService.js +2 -0
  35. package/dist/service/loggerService.d.ts +1 -2
  36. package/dist/service/loggerService.js +1 -10
  37. package/dist/service/middlewareService.d.ts +2 -2
  38. package/dist/service/middlewareService.js +23 -28
  39. package/dist/setup.js +2 -0
  40. package/dist/util/contextUtil.d.ts +1 -1
  41. package/dist/util/index.d.ts +10 -0
  42. package/dist/util/index.js +82 -1
  43. package/dist/util/webRouterParam.d.ts +2 -2
  44. package/dist/util/webRouterParam.js +17 -18
  45. package/package.json +6 -5
  46. package/dist/util/exceptionFilterManager.d.ts +0 -13
  47. package/dist/util/exceptionFilterManager.js +0 -53
  48. package/dist/util/middlewareManager.d.ts +0 -11
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebRouterCollector = void 0;
4
4
  const decorator_1 = require("@midwayjs/decorator");
5
- const index_1 = require("./index");
5
+ const util_1 = require("../util");
6
6
  const container_1 = require("../context/container");
7
7
  const fileDetector_1 = require("./fileDetector");
8
8
  const util = require("util");
@@ -11,7 +11,6 @@ class WebRouterCollector {
11
11
  constructor(baseDir = '', options = {}) {
12
12
  this.isReady = false;
13
13
  this.routes = new Map();
14
- this.routerModules = new Set();
15
14
  this.routesPriority = [];
16
15
  this.baseDir = baseDir;
17
16
  this.options = options;
@@ -34,6 +33,17 @@ class WebRouterCollector {
34
33
  this.collectFunctionRoute(module);
35
34
  }
36
35
  }
36
+ // filter empty prefix
37
+ this.routesPriority = this.routesPriority.filter(item => {
38
+ const prefixList = this.routes.get(item.prefix);
39
+ if (prefixList.length > 0) {
40
+ return true;
41
+ }
42
+ else {
43
+ this.routes.delete(item.prefix);
44
+ return false;
45
+ }
46
+ });
37
47
  // sort router
38
48
  for (const prefix of this.routes.keys()) {
39
49
  const routerInfo = this.routes.get(prefix);
@@ -41,10 +51,11 @@ class WebRouterCollector {
41
51
  }
42
52
  // sort prefix
43
53
  this.routesPriority = this.routesPriority.sort((routeA, routeB) => {
44
- return routeB.priority - routeA.priority;
54
+ return routeB.prefix.length - routeA.prefix.length;
45
55
  });
46
56
  }
47
57
  collectRoute(module, functionMeta = false) {
58
+ var _a;
48
59
  const controllerId = (0, decorator_1.getProviderName)(module);
49
60
  debug(`[core:webCollector]: Found Controller ${controllerId}.`);
50
61
  const id = (0, decorator_1.getProviderUUId)(module);
@@ -52,21 +63,36 @@ class WebRouterCollector {
52
63
  let priority;
53
64
  // implement middleware in controller
54
65
  const middleware = controllerOption.routerOptions.middleware;
55
- const prefix = controllerOption.prefix || '/';
56
- if (prefix === '/' && priority === undefined) {
57
- priority = -999;
66
+ const controllerIgnoreGlobalPrefix = !!((_a = controllerOption.routerOptions) === null || _a === void 0 ? void 0 : _a.ignoreGlobalPrefix);
67
+ let prefix = (0, util_1.joinURLPath)(this.options.globalPrefix, controllerOption.prefix || '/');
68
+ const ignorePrefix = controllerOption.prefix || '/';
69
+ // if controller set ignore global prefix, all router will be ignore too.
70
+ if (controllerIgnoreGlobalPrefix) {
71
+ prefix = ignorePrefix;
58
72
  }
73
+ // set prefix
59
74
  if (!this.routes.has(prefix)) {
60
75
  this.routes.set(prefix, []);
61
76
  this.routesPriority.push({
62
77
  prefix,
63
- priority: priority || 0,
78
+ priority: prefix === '/' && priority === undefined ? -999 : 0,
79
+ middleware,
80
+ routerOptions: controllerOption.routerOptions,
81
+ controllerId,
82
+ routerModule: module,
83
+ });
84
+ }
85
+ // set ignorePrefix
86
+ if (!this.routes.has(ignorePrefix)) {
87
+ this.routes.set(ignorePrefix, []);
88
+ this.routesPriority.push({
89
+ prefix: ignorePrefix,
90
+ priority: ignorePrefix === '/' && priority === undefined ? -999 : 0,
64
91
  middleware,
65
92
  routerOptions: controllerOption.routerOptions,
66
93
  controllerId,
67
94
  routerModule: module,
68
95
  });
69
- this.routerModules.add(module);
70
96
  }
71
97
  const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, module);
72
98
  if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
@@ -75,7 +101,7 @@ class WebRouterCollector {
75
101
  const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter.method) || [];
76
102
  const data = {
77
103
  id,
78
- prefix,
104
+ prefix: webRouter.ignoreGlobalPrefix ? ignorePrefix : prefix,
79
105
  routerName: webRouter.routerName || '',
80
106
  url: webRouter.path,
81
107
  requestMethod: webRouter.requestMethod,
@@ -95,14 +121,14 @@ class WebRouterCollector {
95
121
  data.functionName = controllerId + '-' + webRouter.method;
96
122
  data.functionTriggerName = decorator_1.ServerlessTriggerType.HTTP;
97
123
  data.functionTriggerMetadata = {
98
- path: (0, index_1.joinURLPath)(prefix, webRouter.path.toString()),
124
+ path: (0, util_1.joinURLPath)(prefix, webRouter.path.toString()),
99
125
  method: webRouter.requestMethod,
100
126
  };
101
127
  data.functionMetadata = {
102
128
  functionName: data.functionName,
103
129
  };
104
130
  }
105
- this.checkDuplicateAndPush(prefix, data);
131
+ this.checkDuplicateAndPush(data.prefix, data);
106
132
  }
107
133
  }
108
134
  }
@@ -123,7 +149,6 @@ class WebRouterCollector {
123
149
  controllerId,
124
150
  routerModule: module,
125
151
  });
126
- this.routerModules.add(module);
127
152
  }
128
153
  for (const webRouter of webRouterInfo) {
129
154
  // 新的 @ServerlessTrigger 写法
@@ -204,12 +229,14 @@ class WebRouterCollector {
204
229
  .map(item => {
205
230
  const urlString = item.url.toString();
206
231
  const weightArr = (0, decorator_1.isRegExp)(item.url)
207
- ? urlString.split('/')
232
+ ? urlString.split('\\/')
208
233
  : urlString.split('/');
209
234
  let weight = 0;
210
235
  // 权重,比如通配的不加权,非通配加权,防止通配出现在最前面
211
236
  for (const fragment of weightArr) {
212
- if (fragment.includes(':') || fragment.includes('*')) {
237
+ if (fragment === '' ||
238
+ fragment.includes(':') ||
239
+ fragment.includes('*')) {
213
240
  weight += 0;
214
241
  }
215
242
  else {
@@ -240,12 +267,12 @@ class WebRouterCollector {
240
267
  if (handlerA._category !== handlerB._category) {
241
268
  return handlerB._category - handlerA._category;
242
269
  }
270
+ // 不同权重
271
+ if (handlerA._weight !== handlerB._weight) {
272
+ return handlerB._weight - handlerA._weight;
273
+ }
243
274
  // 不同长度
244
275
  if (handlerA._level === handlerB._level) {
245
- // 不同权重
246
- if (handlerA._weight !== handlerB._weight) {
247
- return handlerB._weight - handlerA._weight;
248
- }
249
276
  if (handlerB._pureRouter === handlerA._pureRouter) {
250
277
  return (handlerA.url.toString().length - handlerB.url.toString().length);
251
278
  }
@@ -274,18 +301,11 @@ class WebRouterCollector {
274
301
  this.isReady = true;
275
302
  }
276
303
  let routeArr = [];
277
- for (const routerInfo of this.routes.values()) {
278
- routeArr = routeArr.concat(routerInfo);
304
+ for (const routerPriority of this.routesPriority) {
305
+ routeArr = routeArr.concat(this.routes.get(routerPriority.prefix));
279
306
  }
280
307
  return routeArr;
281
308
  }
282
- async getRouterModules() {
283
- if (!this.isReady) {
284
- await this.analyze();
285
- this.isReady = true;
286
- }
287
- return Array.from(this.routerModules);
288
- }
289
309
  checkDuplicateAndPush(prefix, routerInfo) {
290
310
  const prefixList = this.routes.get(prefix);
291
311
  const matched = prefixList.filter(item => {
@@ -1,8 +1,10 @@
1
1
  interface ErrorOption {
2
- cause: Error;
2
+ cause?: Error;
3
+ status?: number;
3
4
  }
4
5
  export declare class MidwayError extends Error {
5
6
  code: number;
7
+ status: number;
6
8
  cause: Error;
7
9
  constructor(message: string, options?: ErrorOption);
8
10
  constructor(message: string, code: number, options?: ErrorOption);
@@ -12,6 +12,7 @@ class MidwayError extends Error {
12
12
  this.name = this.constructor.name;
13
13
  this.code = code;
14
14
  this.cause = options === null || options === void 0 ? void 0 : options.cause;
15
+ this.status = options === null || options === void 0 ? void 0 : options.status;
15
16
  }
16
17
  }
17
18
  exports.MidwayError = MidwayError;
@@ -54,6 +54,7 @@ export declare enum FrameworkErrorEnum {
54
54
  PARAM_TYPE = 10002,
55
55
  DEFINITION_NOT_FOUND = 10003,
56
56
  FEATURE_NO_LONGER_SUPPORTED = 10004,
57
- NO_FRAMEWORK_FOUND = 10005
57
+ VALIDATE_FAIL = 10005,
58
+ MISSING_CONFIG = 10006
58
59
  }
59
60
  //# sourceMappingURL=code.d.ts.map
@@ -59,6 +59,7 @@ var FrameworkErrorEnum;
59
59
  FrameworkErrorEnum[FrameworkErrorEnum["PARAM_TYPE"] = 10002] = "PARAM_TYPE";
60
60
  FrameworkErrorEnum[FrameworkErrorEnum["DEFINITION_NOT_FOUND"] = 10003] = "DEFINITION_NOT_FOUND";
61
61
  FrameworkErrorEnum[FrameworkErrorEnum["FEATURE_NO_LONGER_SUPPORTED"] = 10004] = "FEATURE_NO_LONGER_SUPPORTED";
62
- FrameworkErrorEnum[FrameworkErrorEnum["NO_FRAMEWORK_FOUND"] = 10005] = "NO_FRAMEWORK_FOUND";
62
+ FrameworkErrorEnum[FrameworkErrorEnum["VALIDATE_FAIL"] = 10005] = "VALIDATE_FAIL";
63
+ FrameworkErrorEnum[FrameworkErrorEnum["MISSING_CONFIG"] = 10006] = "MISSING_CONFIG";
63
64
  })(FrameworkErrorEnum = exports.FrameworkErrorEnum || (exports.FrameworkErrorEnum = {}));
64
65
  //# sourceMappingURL=code.js.map
@@ -15,7 +15,10 @@ export declare class MidwayDefinitionNotFoundError extends MidwayError {
15
15
  export declare class MidwayFeatureNoLongerSupportedError extends MidwayError {
16
16
  constructor(message?: string);
17
17
  }
18
- export declare class MidwayNoFrameworkFoundError extends MidwayError {
19
- constructor();
18
+ export declare class MidwayValidationError extends MidwayError {
19
+ constructor(message: any, status: any, cause: any);
20
+ }
21
+ export declare class MidwayConfigMissingError extends MidwayError {
22
+ constructor(configKey: string);
20
23
  }
21
24
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayNoFrameworkFoundError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = void 0;
3
+ exports.MidwayConfigMissingError = exports.MidwayValidationError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = void 0;
4
4
  const base_1 = require("./base");
5
5
  const code_1 = require("./code");
6
6
  class MidwayCommonError extends base_1.MidwayError {
@@ -40,10 +40,19 @@ class MidwayFeatureNoLongerSupportedError extends base_1.MidwayError {
40
40
  }
41
41
  }
42
42
  exports.MidwayFeatureNoLongerSupportedError = MidwayFeatureNoLongerSupportedError;
43
- class MidwayNoFrameworkFoundError extends base_1.MidwayError {
44
- constructor() {
45
- super('You must add a component that contains @Framework at least, such as @midwayjs/web, @midwayjs/koa, etc.', code_1.FrameworkErrorEnum.NO_FRAMEWORK_FOUND);
43
+ class MidwayValidationError extends base_1.MidwayError {
44
+ constructor(message, status, cause) {
45
+ super(message, code_1.FrameworkErrorEnum.VALIDATE_FAIL, {
46
+ status,
47
+ cause,
48
+ });
46
49
  }
47
50
  }
48
- exports.MidwayNoFrameworkFoundError = MidwayNoFrameworkFoundError;
51
+ exports.MidwayValidationError = MidwayValidationError;
52
+ class MidwayConfigMissingError extends base_1.MidwayError {
53
+ constructor(configKey) {
54
+ super(`Can't found config key "${configKey}" in your config, please set it first`, code_1.FrameworkErrorEnum.MISSING_CONFIG);
55
+ }
56
+ }
57
+ exports.MidwayConfigMissingError = MidwayConfigMissingError;
49
58
  //# sourceMappingURL=framework.js.map
@@ -1,4 +1,5 @@
1
- export declare class HttpError extends Error {
1
+ import { MidwayError } from './base';
2
+ export declare class HttpError extends MidwayError {
2
3
  status: number;
3
4
  constructor(response: any, status: any);
4
5
  }
@@ -2,10 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.http = exports.GatewayTimeoutError = exports.ServiceUnavailableError = exports.BadGatewayError = exports.InternalServerErrorError = exports.UnprocessableError = exports.UnsupportedMediaTypeError = exports.PayloadTooLargeError = exports.GoneError = exports.ConflictError = exports.RequestTimeoutError = exports.NotAcceptableError = exports.ForbiddenError = exports.NotFoundError = exports.UnauthorizedError = exports.BadRequestError = exports.HttpError = void 0;
4
4
  const code_1 = require("./code");
5
- class HttpError extends Error {
5
+ const base_1 = require("./base");
6
+ class HttpError extends base_1.MidwayError {
6
7
  constructor(response, status) {
7
- super();
8
- this.message = typeof response === 'string' ? response : response.message;
8
+ super(typeof response === 'string' ? response : response.message);
9
9
  this.status = status;
10
10
  this.name = this.constructor.name;
11
11
  }
@@ -1,3 +1,4 @@
1
+ export * from './base';
1
2
  export * from './http';
2
3
  export * from './framework';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -10,6 +10,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./base"), exports);
13
14
  __exportStar(require("./http"), exports);
14
15
  __exportStar(require("./framework"), exports);
15
16
  //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -4,12 +4,11 @@ export { MidwayRequestContainer } from './context/requestContainer';
4
4
  export { BaseFramework } from './baseFramework';
5
5
  export * from './context/providerWrapper';
6
6
  export * from './common/constants';
7
- export { safelyGet, safeRequire, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, deprecatedOutput, } from './util/';
7
+ export { safelyGet, safeRequire, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, deprecatedOutput, transformRequestObjectByType, } from './util/';
8
8
  export * from './util/pathFileUtil';
9
9
  export * from './util/webRouterParam';
10
- export * from './util/webRouterCollector';
11
- export * from './util/triggerCollector';
12
- export { plainToClass, classToPlain } from 'class-transformer';
10
+ export * from './common/webRouterCollector';
11
+ export * from './common/triggerCollector';
13
12
  export { createConfiguration } from './functional/configuration';
14
13
  export { MidwayConfigService } from './service/configService';
15
14
  export { MidwayEnvironmentService } from './service/environmentService';
@@ -22,12 +21,12 @@ export { MidwayMiddlewareService } from './service/middlewareService';
22
21
  export { MidwayDecoratorService } from './service/decoratorService';
23
22
  export * from './service/pipelineService';
24
23
  export * from './util/contextUtil';
25
- export * from './util/serviceFactory';
26
- export * from './util/fileDetector';
27
- export * from './util/webGenerator';
28
- export * from './util/middlewareManager';
24
+ export * from './common/serviceFactory';
25
+ export * from './common/fileDetector';
26
+ export * from './common/webGenerator';
27
+ export * from './common/middlewareManager';
29
28
  export * from './util/pathToRegexp';
30
- export * from './util/exceptionFilterManager';
29
+ export * from './common/filterManager';
31
30
  export * from './setup';
32
31
  export * from './error';
33
32
  /**
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.MidwayFrameworkType = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.classToPlain = exports.plainToClass = exports.deprecatedOutput = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
13
+ exports.MidwayFrameworkType = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
14
14
  __exportStar(require("./interface"), exports);
15
15
  __exportStar(require("./context/container"), exports);
16
16
  var requestContainer_1 = require("./context/requestContainer");
@@ -26,13 +26,11 @@ Object.defineProperty(exports, "delegateTargetPrototypeMethod", { enumerable: tr
26
26
  Object.defineProperty(exports, "delegateTargetMethod", { enumerable: true, get: function () { return util_1.delegateTargetMethod; } });
27
27
  Object.defineProperty(exports, "delegateTargetProperties", { enumerable: true, get: function () { return util_1.delegateTargetProperties; } });
28
28
  Object.defineProperty(exports, "deprecatedOutput", { enumerable: true, get: function () { return util_1.deprecatedOutput; } });
29
+ Object.defineProperty(exports, "transformRequestObjectByType", { enumerable: true, get: function () { return util_1.transformRequestObjectByType; } });
29
30
  __exportStar(require("./util/pathFileUtil"), exports);
30
31
  __exportStar(require("./util/webRouterParam"), exports);
31
- __exportStar(require("./util/webRouterCollector"), exports);
32
- __exportStar(require("./util/triggerCollector"), exports);
33
- var class_transformer_1 = require("class-transformer");
34
- Object.defineProperty(exports, "plainToClass", { enumerable: true, get: function () { return class_transformer_1.plainToClass; } });
35
- Object.defineProperty(exports, "classToPlain", { enumerable: true, get: function () { return class_transformer_1.classToPlain; } });
32
+ __exportStar(require("./common/webRouterCollector"), exports);
33
+ __exportStar(require("./common/triggerCollector"), exports);
36
34
  var configuration_1 = require("./functional/configuration");
37
35
  Object.defineProperty(exports, "createConfiguration", { enumerable: true, get: function () { return configuration_1.createConfiguration; } });
38
36
  var configService_1 = require("./service/configService");
@@ -55,12 +53,12 @@ var decoratorService_1 = require("./service/decoratorService");
55
53
  Object.defineProperty(exports, "MidwayDecoratorService", { enumerable: true, get: function () { return decoratorService_1.MidwayDecoratorService; } });
56
54
  __exportStar(require("./service/pipelineService"), exports);
57
55
  __exportStar(require("./util/contextUtil"), exports);
58
- __exportStar(require("./util/serviceFactory"), exports);
59
- __exportStar(require("./util/fileDetector"), exports);
60
- __exportStar(require("./util/webGenerator"), exports);
61
- __exportStar(require("./util/middlewareManager"), exports);
56
+ __exportStar(require("./common/serviceFactory"), exports);
57
+ __exportStar(require("./common/fileDetector"), exports);
58
+ __exportStar(require("./common/webGenerator"), exports);
59
+ __exportStar(require("./common/middlewareManager"), exports);
62
60
  __exportStar(require("./util/pathToRegexp"), exports);
63
- __exportStar(require("./util/exceptionFilterManager"), exports);
61
+ __exportStar(require("./common/filterManager"), exports);
64
62
  __exportStar(require("./setup"), exports);
65
63
  __exportStar(require("./error"), exports);
66
64
  /**
@@ -2,7 +2,7 @@
2
2
  import { ObjectIdentifier, IManagedInstance, IMethodAspect, ScopeEnum, FrameworkType } from '@midwayjs/decorator';
3
3
  import { ILogger, LoggerOptions } from '@midwayjs/logger';
4
4
  import * as EventEmitter from 'events';
5
- import { ContextMiddlewareManager } from './util/middlewareManager';
5
+ import { ContextMiddlewareManager } from './common/middlewareManager';
6
6
  import _default from './config/config.default';
7
7
  export declare type PowerPartial<T> = {
8
8
  [U in keyof T]?: T[U] extends {} ? PowerPartial<T[U]> : T[U];
@@ -14,16 +14,16 @@ export declare type ServiceFactoryConfigOption<OPTIONS> = {
14
14
  [key: string]: PowerPartial<OPTIONS>;
15
15
  };
16
16
  };
17
- declare type ConfigType<T> = T extends (args: any[]) => any ? PowerPartial<ReturnType<T>> : PowerPartial<T>;
17
+ declare type ConfigType<T> = T extends (...args: any[]) => any ? PowerPartial<ReturnType<T>> : PowerPartial<T>;
18
18
  export declare type FileConfigOption<T, K = unknown> = K extends keyof ConfigType<T> ? Pick<ConfigType<T>, K> : ConfigType<T>;
19
19
  /**
20
20
  * 生命周期定义
21
21
  */
22
22
  export interface ILifeCycle extends Partial<IObjectLifeCycle> {
23
- onConfigLoad?(container: IMidwayContainer, app?: IMidwayApplication): Promise<any>;
24
- onReady?(container: IMidwayContainer, app?: IMidwayApplication): Promise<void>;
25
- onServerReady?(container: IMidwayContainer, app?: IMidwayApplication): Promise<void>;
26
- onStop?(container: IMidwayContainer, app?: IMidwayApplication): Promise<void>;
23
+ onConfigLoad?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<any>;
24
+ onReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
25
+ onServerReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
26
+ onStop?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
27
27
  }
28
28
  export declare type ObjectContext = {
29
29
  originName?: string;
@@ -185,6 +185,7 @@ export declare type ParameterHandlerFunction = (options: {
185
185
  propertyName: string;
186
186
  metadata: any;
187
187
  originArgs: Array<any>;
188
+ originParamType: any;
188
189
  parameterIndex: number;
189
190
  }) => IMethodAspect;
190
191
  export interface IIdentifierRelationShip {
@@ -273,30 +274,32 @@ export interface Context {
273
274
  getAttr<T>(key: string): T;
274
275
  }
275
276
  export declare type IMidwayContext<FrameworkContext = unknown> = Context & FrameworkContext;
277
+ export declare type NextFunction = () => Promise<any>;
276
278
  /**
277
279
  * Common middleware definition
278
280
  */
279
- export interface IMiddleware<T, R = any, N = any> {
280
- resolve: () => FunctionMiddleware<T, R, N>;
281
- match?: () => boolean;
282
- ignore?: () => boolean;
281
+ export interface IMiddleware<CTX, R, N = unknown> {
282
+ resolve: () => FunctionMiddleware<CTX, R, N>;
283
+ match?: (ctx?: CTX) => boolean;
284
+ ignore?: (ctx?: CTX) => boolean;
283
285
  }
284
- export declare type FunctionMiddleware<T, R = any, N = any> = ((context: T, next: () => Promise<any>, options?: any) => any) | ((req: T, res: R, next: N) => any);
285
- export declare type ClassMiddleware<T, R = any, N = any> = new (...args: any[]) => IMiddleware<T, R, N>;
286
- export declare type CommonMiddleware<T, R = any, N = any> = ClassMiddleware<T, R, N> | FunctionMiddleware<T, R, N>;
287
- export declare type CommonMiddlewareUnion<T, R = any, N = any> = CommonMiddleware<T, R, N> | Array<CommonMiddleware<T, R, N>>;
288
- export declare type MiddlewareRespond<T, R = any, N = any> = (context: T, nextOrRes?: () => Promise<any> | R, next?: N) => Promise<{
286
+ export declare type FunctionMiddleware<CTX, R, N = unknown> = N extends true ? (req: CTX, res: R, next: N) => any : (context: CTX, next: R, options?: any) => any;
287
+ export declare type ClassMiddleware<CTX, R, N> = new (...args: any[]) => IMiddleware<CTX, R, N>;
288
+ export declare type CommonMiddleware<CTX, R, N> = ClassMiddleware<CTX, R, N> | FunctionMiddleware<CTX, R, N>;
289
+ export declare type CommonMiddlewareUnion<CTX, R, N> = CommonMiddleware<CTX, R, N> | Array<CommonMiddleware<CTX, R, N>>;
290
+ export declare type MiddlewareRespond<CTX, R, N> = (context: CTX, nextOrRes?: N extends true ? R : NextFunction, next?: N) => Promise<{
289
291
  result: any;
290
292
  error: Error | undefined;
291
293
  }>;
292
294
  /**
293
295
  * Common Exception Filter definition
294
296
  */
295
- export interface IExceptionFilter<T, R = any, N = any> {
296
- catch(err: Error, ctx: T, res?: R, next?: N): any;
297
+ export interface IFilter<CTX, R, N> {
298
+ catch?(err: Error, ctx: CTX, res?: R, next?: N): any;
299
+ match?(result: any, ctx: CTX, res?: R, next?: N): any;
297
300
  }
298
- export declare type CommonExceptionFilterUnion<T, R = any, N = any> = (new (...args: any[]) => IExceptionFilter<T, R, N>) | Array<new (...args: any[]) => IExceptionFilter<T, R, N>>;
299
- export interface IMidwayBaseApplication<T extends IMidwayContext = IMidwayContext> {
301
+ export declare type CommonFilterUnion<CTX, R, N> = (new (...args: any[]) => IFilter<CTX, R, N>) | Array<new (...args: any[]) => IFilter<CTX, R, N>>;
302
+ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
300
303
  /**
301
304
  * Get a base directory for project, with src or dist
302
305
  */
@@ -349,7 +352,7 @@ export interface IMidwayBaseApplication<T extends IMidwayContext = IMidwayContex
349
352
  * create a context with RequestContainer
350
353
  * @param args
351
354
  */
352
- createAnonymousContext(...args: any[]): T;
355
+ createAnonymousContext(...args: any[]): CTX;
353
356
  /**
354
357
  * Set a context logger class to change default context logger format
355
358
  * @param BaseContextLoggerClass
@@ -375,16 +378,16 @@ export interface IMidwayBaseApplication<T extends IMidwayContext = IMidwayContex
375
378
  * add global filter to app
376
379
  * @param Middleware
377
380
  */
378
- useMiddleware<R = any, N = any>(Middleware: CommonMiddlewareUnion<T, R, N>): void;
381
+ useMiddleware<R, N>(Middleware: CommonMiddlewareUnion<CTX, R, N>): void;
379
382
  /**
380
383
  * get global middleware
381
384
  */
382
- getMiddleware<R = any, N = any>(): ContextMiddlewareManager<T, R, N>;
385
+ getMiddleware<R, N>(): ContextMiddlewareManager<CTX, R, N>;
383
386
  /**
384
387
  * add exception filter
385
388
  * @param Filter
386
389
  */
387
- useFilter(Filter: CommonExceptionFilterUnion<T>): void;
390
+ useFilter<R, N>(Filter: CommonFilterUnion<CTX, R, N>): void;
388
391
  }
389
392
  export declare type IMidwayApplication<T extends IMidwayContext = IMidwayContext, FrameworkApplication = unknown> = IMidwayBaseApplication<T> & FrameworkApplication;
390
393
  export interface IMidwayBootstrapOptions {
@@ -407,10 +410,10 @@ export interface IConfigurationOptions {
407
410
  ContextLoggerClass?: any;
408
411
  ContextLoggerApplyLogger?: string;
409
412
  }
410
- export interface IMidwayFramework<APP extends IMidwayApplication, T extends IConfigurationOptions> {
413
+ export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX extends IMidwayContext, CONFIG extends IConfigurationOptions, ResOrNext = unknown, Next = unknown> {
411
414
  app: APP;
412
- configurationOptions: T;
413
- configure(options?: T): any;
415
+ configurationOptions: CONFIG;
416
+ configure(options?: CONFIG): any;
414
417
  isEnable(): boolean;
415
418
  initialize(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
416
419
  run(): Promise<void>;
@@ -428,9 +431,9 @@ export interface IMidwayFramework<APP extends IMidwayApplication, T extends ICon
428
431
  createLogger(name: string, options: LoggerOptions): ILogger;
429
432
  getProjectName(): string;
430
433
  getDefaultContextLoggerClass(): any;
431
- useMiddleware(Middleware: CommonMiddlewareUnion<ReturnType<APP['createAnonymousContext']>>): any;
432
- getMiddleware<R, N>(lastMiddleware?: CommonMiddleware<ReturnType<APP['createAnonymousContext']>>): Promise<MiddlewareRespond<ReturnType<APP['createAnonymousContext']>, R, N>>;
433
- useFilter(Filter: CommonExceptionFilterUnion<ReturnType<APP['createAnonymousContext']>>): any;
434
+ useMiddleware(Middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
435
+ getMiddleware(lastMiddleware?: CommonMiddleware<CTX, ResOrNext, Next>): Promise<MiddlewareRespond<CTX, ResOrNext, Next>>;
436
+ useFilter(Filter: CommonFilterUnion<CTX, ResOrNext, Next>): any;
434
437
  }
435
438
  export declare const MIDWAY_LOGGER_WRITEABLE_DIR = "MIDWAY_LOGGER_WRITEABLE_DIR";
436
439
  export interface MidwayAppInfo {
@@ -24,7 +24,27 @@ let MidwayDecoratorService = class MidwayDecoratorService {
24
24
  }
25
25
  async init() {
26
26
  // add custom method decorator listener
27
- this.applicationContext.onBeforeBind((Clzz, options) => {
27
+ this.applicationContext.onBeforeBind(Clzz => {
28
+ // find custom method decorator metadata, include method decorator information array
29
+ const methodDecoratorMetadataList = (0, decorator_1.getClassMetadata)(decorator_1.INJECT_CUSTOM_METHOD, Clzz);
30
+ if (methodDecoratorMetadataList) {
31
+ // loop it, save this order for decorator run
32
+ for (const meta of methodDecoratorMetadataList) {
33
+ const { propertyName, key, metadata } = meta;
34
+ // add aspect implementation first
35
+ this.aspectService.interceptPrototypeMethod(Clzz, propertyName, () => {
36
+ const methodDecoratorHandler = this.methodDecoratorMap.get(key);
37
+ if (!methodDecoratorHandler) {
38
+ throw new error_1.MidwayCommonError(`Method Decorator "${key}" handler not found, please register first.`);
39
+ }
40
+ return this.methodDecoratorMap.get(key)({
41
+ target: Clzz,
42
+ propertyName,
43
+ metadata,
44
+ });
45
+ });
46
+ }
47
+ }
28
48
  // find custom param decorator metadata
29
49
  const parameterDecoratorMetadata = (0, decorator_1.getClassMetadata)(decorator_1.INJECT_CUSTOM_PARAM, Clzz);
30
50
  if (parameterDecoratorMetadata) {
@@ -42,12 +62,14 @@ let MidwayDecoratorService = class MidwayDecoratorService {
42
62
  if (!parameterDecoratorHandler) {
43
63
  throw new error_1.MidwayCommonError(`Parameter Decorator "${key}" handler not found, please register first.`);
44
64
  }
65
+ const paramTypes = (0, decorator_1.getMethodParamTypes)(Clzz, propertyName);
45
66
  newArgs[parameterIndex] = await parameterDecoratorHandler({
46
67
  metadata,
47
68
  propertyName,
48
69
  parameterIndex,
49
70
  target: Clzz,
50
71
  originArgs: joinPoint.args,
72
+ originParamType: paramTypes[parameterIndex],
51
73
  });
52
74
  }
53
75
  joinPoint.args = newArgs;
@@ -56,26 +78,6 @@ let MidwayDecoratorService = class MidwayDecoratorService {
56
78
  });
57
79
  }
58
80
  }
59
- // find custom method decorator metadata, include method decorator information array
60
- const methodDecoratorMetadataList = (0, decorator_1.getClassMetadata)(decorator_1.INJECT_CUSTOM_METHOD, Clzz);
61
- if (methodDecoratorMetadataList) {
62
- // loop it, save this order for decorator run
63
- for (const meta of methodDecoratorMetadataList) {
64
- const { propertyName, key, metadata } = meta;
65
- // add aspect implementation first
66
- this.aspectService.interceptPrototypeMethod(Clzz, propertyName, () => {
67
- const methodDecoratorHandler = this.methodDecoratorMap.get(key);
68
- if (!methodDecoratorHandler) {
69
- throw new error_1.MidwayCommonError(`Method Decorator "${key}" handler not found, please register first.`);
70
- }
71
- return this.methodDecoratorMap.get(key)({
72
- target: Clzz,
73
- propertyName,
74
- metadata,
75
- });
76
- });
77
- }
78
- }
79
81
  });
80
82
  // add custom property decorator listener
81
83
  this.applicationContext.onObjectCreated((instance, options) => {
@@ -15,10 +15,11 @@ export declare class MidwayFrameworkService {
15
15
  private mainFramework;
16
16
  private globalFrameworkMap;
17
17
  private globalFrameworkList;
18
- init(): Promise<void>;
18
+ protected init(): Promise<void>;
19
19
  getMainApp(): any;
20
- getMainFramework(): IMidwayFramework<any, any>;
21
- getFramework(type: MidwayFrameworkType): IMidwayFramework<any, any>;
20
+ getMainFramework(): IMidwayFramework<any, any, any, unknown, unknown>;
21
+ getFramework(type: MidwayFrameworkType): IMidwayFramework<any, any, any, unknown, unknown>;
22
+ runFramework(): Promise<void>;
22
23
  stopFramework(): Promise<void>;
23
24
  }
24
25
  //# sourceMappingURL=frameworkService.d.ts.map
@@ -110,6 +110,16 @@ let MidwayFrameworkService = class MidwayFrameworkService {
110
110
  getFramework(type) {
111
111
  return this.globalFrameworkMap.get(type);
112
112
  }
113
+ async runFramework() {
114
+ for (const frameworkInstance of this.globalFrameworkList) {
115
+ // if enable, just init framework
116
+ if (frameworkInstance.isEnable()) {
117
+ // app init
118
+ await frameworkInstance.run();
119
+ debug(`[core:framework]: Found Framework "${frameworkInstance.getFrameworkName()}" and run.`);
120
+ }
121
+ }
122
+ }
113
123
  async stopFramework() {
114
124
  await Promise.all(Array.from(this.globalFrameworkList).map(frameworkInstance => {
115
125
  return frameworkInstance.stop();
@@ -54,6 +54,8 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
54
54
  });
55
55
  // exec onReady()
56
56
  await this.runContainerLifeCycle(lifecycleInstanceList, 'onReady');
57
+ // exec framework.run()
58
+ await this.frameworkService.runFramework();
57
59
  // exec onServerReady()
58
60
  await this.runContainerLifeCycle(lifecycleInstanceList, 'onServerReady');
59
61
  }