@midwayjs/core 3.3.6 → 3.4.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -13,6 +13,7 @@ export declare class DirectoryFileDetector extends AbstractFileDetector<{
13
13
  namespace: string;
14
14
  }> {
15
15
  private directoryFilterArray;
16
+ private duplicateModuleCheckSet;
16
17
  run(container: any): void;
17
18
  }
18
19
  export declare class CustomModuleDetector extends AbstractFileDetector<{
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CustomModuleDetector = exports.DirectoryFileDetector = exports.AbstractFileDetector = void 0;
4
4
  const decorator_1 = require("@midwayjs/decorator");
5
5
  const glob_1 = require("@midwayjs/glob");
6
+ const error_1 = require("../error");
6
7
  class AbstractFileDetector {
7
8
  constructor(options) {
8
9
  this.options = options;
@@ -31,6 +32,7 @@ class DirectoryFileDetector extends AbstractFileDetector {
31
32
  constructor() {
32
33
  super(...arguments);
33
34
  this.directoryFilterArray = [];
35
+ this.duplicateModuleCheckSet = new Map();
34
36
  }
35
37
  run(container) {
36
38
  const loadDirs = []
@@ -41,6 +43,20 @@ class DirectoryFileDetector extends AbstractFileDetector {
41
43
  cwd: dir,
42
44
  ignore: DEFAULT_IGNORE_PATTERN.concat(this.options.ignore || []).concat(this.extraDetectorOptions.ignore || []),
43
45
  });
46
+ // 检查重复模块
47
+ const checkDuplicatedHandler = (module, options) => {
48
+ if (decorator_1.Types.isClass(module)) {
49
+ const name = (0, decorator_1.getProviderName)(module);
50
+ if (name) {
51
+ if (this.duplicateModuleCheckSet.has(name)) {
52
+ throw new error_1.MidwayDuplicateClassNameError(name, options.srcPath, this.duplicateModuleCheckSet.get(name));
53
+ }
54
+ else {
55
+ this.duplicateModuleCheckSet.set(name, options.srcPath);
56
+ }
57
+ }
58
+ }
59
+ };
44
60
  for (const file of fileResults) {
45
61
  if (this.directoryFilterArray.length) {
46
62
  for (const resolveFilter of this.directoryFilterArray) {
@@ -68,6 +84,7 @@ class DirectoryFileDetector extends AbstractFileDetector {
68
84
  namespace: this.options.namespace,
69
85
  srcPath: file,
70
86
  createFrom: 'file',
87
+ bindHook: checkDuplicatedHandler,
71
88
  });
72
89
  }
73
90
  }
@@ -78,10 +95,13 @@ class DirectoryFileDetector extends AbstractFileDetector {
78
95
  namespace: this.options.namespace,
79
96
  srcPath: file,
80
97
  createFrom: 'file',
98
+ bindHook: checkDuplicatedHandler,
81
99
  });
82
100
  }
83
101
  }
84
102
  }
103
+ // check end
104
+ this.duplicateModuleCheckSet.clear();
85
105
  }
86
106
  }
87
107
  exports.DirectoryFileDetector = DirectoryFileDetector;
@@ -5,6 +5,7 @@ export declare class FilterManager<CTX extends IMidwayContext = IMidwayContext,
5
5
  private exceptionMap;
6
6
  private defaultErrFilter;
7
7
  private matchFnList;
8
+ private protoMatchList;
8
9
  useFilter(Filters: CommonFilterUnion<CTX, R, N>): void;
9
10
  init(applicationContext: IMidwayContainer): Promise<void>;
10
11
  runErrorFilter(err: Error, ctx: CTX, res?: R, next?: N): Promise<{
@@ -10,6 +10,7 @@ class FilterManager {
10
10
  this.exceptionMap = new WeakMap();
11
11
  this.defaultErrFilter = undefined;
12
12
  this.matchFnList = [];
13
+ this.protoMatchList = [];
13
14
  }
14
15
  useFilter(Filters) {
15
16
  if (!Array.isArray(Filters)) {
@@ -31,7 +32,20 @@ class FilterManager {
31
32
  const exceptionMetadata = (0, decorator_1.getClassMetadata)(decorator_1.CATCH_KEY, FilterClass);
32
33
  if (exceptionMetadata && exceptionMetadata.catchTargets) {
33
34
  for (const Exception of exceptionMetadata.catchTargets) {
34
- this.exceptionMap.set(Exception, filter);
35
+ this.exceptionMap.set(Exception, {
36
+ filter,
37
+ catchOptions: exceptionMetadata.catchOptions || {},
38
+ });
39
+ if (exceptionMetadata.catchOptions['matchPrototype']) {
40
+ this.protoMatchList.push(err => {
41
+ if (err instanceof Exception) {
42
+ return Exception;
43
+ }
44
+ else {
45
+ return false;
46
+ }
47
+ });
48
+ }
35
49
  }
36
50
  }
37
51
  else {
@@ -53,14 +67,32 @@ class FilterManager {
53
67
  }
54
68
  async runErrorFilter(err, ctx, res, next) {
55
69
  let result, error;
70
+ let matched = false;
56
71
  if (this.exceptionMap.has(err.constructor)) {
57
- const filter = this.exceptionMap.get(err.constructor);
58
- result = await filter.catch(err, ctx, res, next);
72
+ matched = true;
73
+ const filterData = this.exceptionMap.get(err.constructor);
74
+ result = await filterData.filter.catch(err, ctx, res, next);
59
75
  }
60
- else if (this.defaultErrFilter) {
76
+ // match with prototype
77
+ if (!matched && this.protoMatchList.length) {
78
+ let protoException;
79
+ for (const matchPattern of this.protoMatchList) {
80
+ protoException = matchPattern(err);
81
+ if (protoException) {
82
+ break;
83
+ }
84
+ }
85
+ if (protoException) {
86
+ matched = true;
87
+ const filterData = this.exceptionMap.get(protoException);
88
+ result = await filterData.filter.catch(err, ctx, res, next);
89
+ }
90
+ }
91
+ if (!matched && this.defaultErrFilter) {
92
+ matched = true;
61
93
  result = await this.defaultErrFilter.catch(err, ctx, res, next);
62
94
  }
63
- else {
95
+ if (!matched) {
64
96
  error = err;
65
97
  }
66
98
  return {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ServiceFactory = void 0;
4
4
  const assert = require("assert");
5
+ const extend_1 = require("../util/extend");
5
6
  /**
6
7
  * 多客户端工厂实现
7
8
  */
@@ -33,7 +34,7 @@ class ServiceFactory {
33
34
  }
34
35
  async createInstance(config, clientName) {
35
36
  // options.default will be merge in to options.clients[id]
36
- config = Object.assign({}, this.options['default'], config);
37
+ config = (0, extend_1.extend)(true, {}, this.options['default'], config);
37
38
  const client = await this.createClient(config, clientName);
38
39
  if (client) {
39
40
  if (clientName) {
@@ -1,15 +1,16 @@
1
- import { RouterInfo, IMidwayApplication } from '../index';
1
+ import { MidwayWebRouterService, RouterInfo, IMidwayApplication } from '../index';
2
2
  export declare abstract class WebControllerGenerator<Router extends {
3
3
  use: (...args: any[]) => void;
4
4
  }> {
5
5
  readonly app: IMidwayApplication;
6
- protected constructor(app: IMidwayApplication);
6
+ readonly midwayWebRouterService: MidwayWebRouterService;
7
+ protected constructor(app: IMidwayApplication, midwayWebRouterService: MidwayWebRouterService);
7
8
  /**
8
9
  * wrap controller string to middleware function
9
10
  * @param routeInfo
10
11
  */
11
12
  generateKoaController(routeInfo: RouterInfo): (ctx: any, next: any) => Promise<void>;
12
- loadMidwayController(globalPrefix: string, routerHandler?: (newRouter: Router) => void): Promise<void>;
13
+ loadMidwayController(routerHandler?: (newRouter: Router) => void): Promise<void>;
13
14
  abstract createRouter(routerOptions: any): Router;
14
15
  abstract generateController(routeInfo: RouterInfo): any;
15
16
  }
@@ -12,8 +12,9 @@ const index_1 = require("../index");
12
12
  const util = require("util");
13
13
  const debug = util.debuglog('midway:debug');
14
14
  class WebControllerGenerator {
15
- constructor(app) {
15
+ constructor(app, midwayWebRouterService) {
16
16
  this.app = app;
17
+ this.midwayWebRouterService = midwayWebRouterService;
17
18
  }
18
19
  /**
19
20
  * wrap controller string to middleware function
@@ -22,14 +23,24 @@ class WebControllerGenerator {
22
23
  generateKoaController(routeInfo) {
23
24
  return async (ctx, next) => {
24
25
  const args = [ctx, next];
25
- const controller = await ctx.requestContext.getAsync(routeInfo.id);
26
- // eslint-disable-next-line prefer-spread
27
- const result = await controller[routeInfo.method].apply(controller, args);
28
- if (result !== undefined) {
29
- ctx.body = result;
26
+ let result;
27
+ if (typeof routeInfo.method !== 'string') {
28
+ result = await routeInfo.method(ctx, next);
29
+ }
30
+ else {
31
+ const controller = await ctx.requestContext.getAsync(routeInfo.id);
32
+ // eslint-disable-next-line prefer-spread
33
+ result = await controller[routeInfo.method].apply(controller, args);
30
34
  }
31
- if (ctx.body === undefined && !ctx.response._explicitStatus) {
32
- ctx.body = undefined;
35
+ if (result !== undefined) {
36
+ if (result === null) {
37
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
38
+ ctx.response._body = null;
39
+ ctx.response._midwayControllerNullBody = true;
40
+ }
41
+ else {
42
+ ctx.body = result;
43
+ }
33
44
  }
34
45
  // implement response decorator
35
46
  if (Array.isArray(routeInfo.responseMetadata) &&
@@ -56,13 +67,10 @@ class WebControllerGenerator {
56
67
  }
57
68
  };
58
69
  }
59
- async loadMidwayController(globalPrefix, routerHandler) {
70
+ async loadMidwayController(routerHandler) {
60
71
  var _a, _b;
61
- const collector = new index_1.WebRouterCollector('', {
62
- globalPrefix,
63
- });
64
- const routerTable = await collector.getRouterTable();
65
- const routerList = await collector.getRoutePriorityList();
72
+ const routerTable = await this.midwayWebRouterService.getRouterTable();
73
+ const routerList = await this.midwayWebRouterService.getRoutePriorityList();
66
74
  const applicationContext = this.app.getApplicationContext();
67
75
  const logger = this.app.getCoreLogger();
68
76
  const middlewareService = applicationContext.get(index_1.MidwayMiddlewareService);
@@ -274,6 +274,9 @@ class MidwayContainer {
274
274
  // 如果 definition 存在就不再重复 bind
275
275
  return;
276
276
  }
277
+ if (options === null || options === void 0 ? void 0 : options.bindHook) {
278
+ options.bindHook(target, options);
279
+ }
277
280
  let definition;
278
281
  if (decorator_1.Types.isClass(target)) {
279
282
  definition = new objectDefinition_1.ObjectDefinition();
@@ -16,6 +16,8 @@ export declare const FrameworkErrorEnum: {
16
16
  readonly UTIL_HTTP_TIMEOUT: "MIDWAY_10012";
17
17
  readonly INCONSISTENT_VERSION: "MIDWAY_10013";
18
18
  readonly INVALID_CONFIG: "MIDWAY_10014";
19
+ readonly DUPLICATE_CLASS_NAME: "MIDWAY_10015";
20
+ readonly DUPLICATE_CONTROLLER_PREFIX_OPTIONS: "MIDWAY_10016";
19
21
  };
20
22
  export declare class MidwayCommonError extends MidwayError {
21
23
  constructor(message: string);
@@ -62,4 +64,10 @@ export declare class MidwayUtilHttpClientTimeoutError extends MidwayError {
62
64
  export declare class MidwayInconsistentVersionError extends MidwayError {
63
65
  constructor();
64
66
  }
67
+ export declare class MidwayDuplicateClassNameError extends MidwayError {
68
+ constructor(className: string, existPath: string, existPathOther: string);
69
+ }
70
+ export declare class MidwayDuplicateControllerOptionsError extends MidwayError {
71
+ constructor(prefix: string, existController: string, existControllerOther: string);
72
+ }
65
73
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayInvalidConfigError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
3
+ exports.MidwayDuplicateControllerOptionsError = exports.MidwayDuplicateClassNameError = exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayInvalidConfigError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
4
4
  const base_1 = require("./base");
5
5
  exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
6
6
  UNKNOWN: 10000,
@@ -18,6 +18,8 @@ exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
18
18
  UTIL_HTTP_TIMEOUT: 10012,
19
19
  INCONSISTENT_VERSION: 10013,
20
20
  INVALID_CONFIG: 10014,
21
+ DUPLICATE_CLASS_NAME: 10015,
22
+ DUPLICATE_CONTROLLER_PREFIX_OPTIONS: 10016,
21
23
  });
22
24
  class MidwayCommonError extends base_1.MidwayError {
23
25
  constructor(message) {
@@ -122,4 +124,16 @@ class MidwayInconsistentVersionError extends base_1.MidwayError {
122
124
  }
123
125
  }
124
126
  exports.MidwayInconsistentVersionError = MidwayInconsistentVersionError;
127
+ class MidwayDuplicateClassNameError extends base_1.MidwayError {
128
+ constructor(className, existPath, existPathOther) {
129
+ super(`"${className}" duplicated between "${existPath}" and "${existPathOther}"`, exports.FrameworkErrorEnum.DUPLICATE_CLASS_NAME);
130
+ }
131
+ }
132
+ exports.MidwayDuplicateClassNameError = MidwayDuplicateClassNameError;
133
+ class MidwayDuplicateControllerOptionsError extends base_1.MidwayError {
134
+ constructor(prefix, existController, existControllerOther) {
135
+ super(`"Prefix ${prefix}" with duplicated controller options between "${existController}" and "${existControllerOther}"`, exports.FrameworkErrorEnum.DUPLICATE_CONTROLLER_PREFIX_OPTIONS);
136
+ }
137
+ }
138
+ exports.MidwayDuplicateControllerOptionsError = MidwayDuplicateControllerOptionsError;
125
139
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -4,12 +4,10 @@ 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, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, } from './util/';
7
+ export { safelyGet, safeRequire, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, } from './util/';
8
8
  export { extend } from './util/extend';
9
9
  export * from './util/pathFileUtil';
10
10
  export * from './util/webRouterParam';
11
- export * from './common/webRouterCollector';
12
- export * from './common/triggerCollector';
13
11
  export { createConfiguration } from './functional/configuration';
14
12
  export { MidwayConfigService } from './service/configService';
15
13
  export { MidwayEnvironmentService } from './service/environmentService';
@@ -21,9 +19,11 @@ export { MidwayLifeCycleService } from './service/lifeCycleService';
21
19
  export { MidwayMiddlewareService } from './service/middlewareService';
22
20
  export { MidwayDecoratorService } from './service/decoratorService';
23
21
  export { MidwayMockService } from './service/mockService';
22
+ export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions, MidwayWebRouterService, WebRouterCollector, } from './service/webRouterService';
24
23
  export * from './service/pipelineService';
25
24
  export * from './util/contextUtil';
26
25
  export * from './common/serviceFactory';
26
+ export * from './common/dataSourceManager';
27
27
  export * from './common/dataListener';
28
28
  export * from './common/fileDetector';
29
29
  export * from './common/webGenerator';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.MidwayFrameworkType = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.extend = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
17
+ exports.MidwayFrameworkType = exports.WebRouterCollector = exports.MidwayWebRouterService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.extend = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
18
18
  __exportStar(require("./interface"), exports);
19
19
  __exportStar(require("./context/container"), exports);
20
20
  var requestContainer_1 = require("./context/requestContainer");
@@ -34,12 +34,11 @@ Object.defineProperty(exports, "deprecatedOutput", { enumerable: true, get: func
34
34
  Object.defineProperty(exports, "transformRequestObjectByType", { enumerable: true, get: function () { return util_1.transformRequestObjectByType; } });
35
35
  Object.defineProperty(exports, "pathMatching", { enumerable: true, get: function () { return util_1.pathMatching; } });
36
36
  Object.defineProperty(exports, "wrapMiddleware", { enumerable: true, get: function () { return util_1.wrapMiddleware; } });
37
+ Object.defineProperty(exports, "wrapAsync", { enumerable: true, get: function () { return util_1.wrapAsync; } });
37
38
  var extend_1 = require("./util/extend");
38
39
  Object.defineProperty(exports, "extend", { enumerable: true, get: function () { return extend_1.extend; } });
39
40
  __exportStar(require("./util/pathFileUtil"), exports);
40
41
  __exportStar(require("./util/webRouterParam"), exports);
41
- __exportStar(require("./common/webRouterCollector"), exports);
42
- __exportStar(require("./common/triggerCollector"), exports);
43
42
  var configuration_1 = require("./functional/configuration");
44
43
  Object.defineProperty(exports, "createConfiguration", { enumerable: true, get: function () { return configuration_1.createConfiguration; } });
45
44
  var configService_1 = require("./service/configService");
@@ -62,9 +61,13 @@ var decoratorService_1 = require("./service/decoratorService");
62
61
  Object.defineProperty(exports, "MidwayDecoratorService", { enumerable: true, get: function () { return decoratorService_1.MidwayDecoratorService; } });
63
62
  var mockService_1 = require("./service/mockService");
64
63
  Object.defineProperty(exports, "MidwayMockService", { enumerable: true, get: function () { return mockService_1.MidwayMockService; } });
64
+ var webRouterService_1 = require("./service/webRouterService");
65
+ Object.defineProperty(exports, "MidwayWebRouterService", { enumerable: true, get: function () { return webRouterService_1.MidwayWebRouterService; } });
66
+ Object.defineProperty(exports, "WebRouterCollector", { enumerable: true, get: function () { return webRouterService_1.WebRouterCollector; } });
65
67
  __exportStar(require("./service/pipelineService"), exports);
66
68
  __exportStar(require("./util/contextUtil"), exports);
67
69
  __exportStar(require("./common/serviceFactory"), exports);
70
+ __exportStar(require("./common/dataSourceManager"), exports);
68
71
  __exportStar(require("./common/dataListener"), exports);
69
72
  __exportStar(require("./common/fileDetector"), exports);
70
73
  __exportStar(require("./common/webGenerator"), exports);
@@ -14,6 +14,14 @@ export declare type ServiceFactoryConfigOption<OPTIONS> = {
14
14
  [key: string]: PowerPartial<OPTIONS>;
15
15
  };
16
16
  };
17
+ export declare type DataSourceManagerConfigOption<OPTIONS> = {
18
+ default?: PowerPartial<OPTIONS>;
19
+ dataSource?: {
20
+ [key: string]: PowerPartial<{
21
+ entities: any[];
22
+ } & OPTIONS>;
23
+ };
24
+ };
17
25
  declare type ConfigType<T> = T extends (...args: any[]) => any ? Writable<PowerPartial<ReturnType<T>>> : Writable<PowerPartial<T>>;
18
26
  /**
19
27
  * Get definition from config
@@ -127,6 +135,7 @@ export interface IObjectDefinition {
127
135
  }>;
128
136
  createFrom: 'framework' | 'file' | 'module';
129
137
  allowDowngrade: boolean;
138
+ bindHook?: (module: any, options?: IObjectDefinition) => void;
130
139
  }
131
140
  export interface IObjectCreator {
132
141
  load(): any;
@@ -305,10 +314,7 @@ export declare type FunctionMiddleware<CTX, R, N = unknown> = N extends true ? (
305
314
  export declare type ClassMiddleware<CTX, R, N> = new (...args: any[]) => IMiddleware<CTX, R, N>;
306
315
  export declare type CommonMiddleware<CTX, R, N> = ClassMiddleware<CTX, R, N> | FunctionMiddleware<CTX, R, N>;
307
316
  export declare type CommonMiddlewareUnion<CTX, R, N> = CommonMiddleware<CTX, R, N> | Array<CommonMiddleware<CTX, R, N>>;
308
- export declare type MiddlewareRespond<CTX, R, N> = (context: CTX, nextOrRes?: N extends true ? R : NextFunction, next?: N) => Promise<{
309
- result: any;
310
- error: Error | undefined;
311
- }>;
317
+ export declare type MiddlewareRespond<CTX, R, N> = (context: CTX, nextOrRes?: N extends true ? R : NextFunction, next?: N) => Promise<any>;
312
318
  /**
313
319
  * Common Exception Filter definition
314
320
  */
@@ -88,13 +88,17 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
88
88
  return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
89
89
  index,
90
90
  })).then(result => {
91
- // need to set body
92
- if (context['body'] && !result) {
93
- result = context['body'];
94
- }
95
- else if (result && context['body'] !== result) {
91
+ /**
92
+ * 1、return ctx.body,return 的优先级更高
93
+ * 2、如果 result 有值(非 undefined),则不管什么情况,都会覆盖当前 body,注意,这里有可能赋值 null,导致 status 为 204,会在中间件处进行修正
94
+ * 3、如果 result 没值,且 ctx.body 已经赋值,则向 result 赋值
95
+ */
96
+ if (result !== undefined) {
96
97
  context['body'] = result;
97
98
  }
99
+ else if (context['body'] !== undefined) {
100
+ result = context['body'];
101
+ }
98
102
  return result;
99
103
  });
100
104
  }
@@ -1,16 +1,17 @@
1
+ import { ControllerOption } from '@midwayjs/decorator';
1
2
  export interface RouterInfo {
2
3
  /**
3
4
  * uuid
4
5
  */
5
- id: string;
6
+ id?: string;
6
7
  /**
7
8
  * router prefix from controller
8
9
  */
9
- prefix: string;
10
+ prefix?: string;
10
11
  /**
11
12
  * router alias name
12
13
  */
13
- routerName: string;
14
+ routerName?: string;
14
15
  /**
15
16
  * router path, without prefix
16
17
  */
@@ -22,40 +23,40 @@ export interface RouterInfo {
22
23
  /**
23
24
  * invoke function method
24
25
  */
25
- method: string;
26
+ method: string | ((...args: any[]) => void);
26
27
  /**
27
28
  * router description
28
29
  */
29
- description: string;
30
- summary: string;
30
+ description?: string;
31
+ summary?: string;
31
32
  /**
32
33
  * router handler function key,for IoC container load
33
34
  */
34
- handlerName: string;
35
+ handlerName?: string;
35
36
  /**
36
37
  * serverless func load key
37
38
  */
38
- funcHandlerName: string;
39
+ funcHandlerName?: string;
39
40
  /**
40
41
  * controller provideId
41
42
  */
42
- controllerId: string;
43
+ controllerId?: string;
43
44
  /**
44
45
  * router middleware
45
46
  */
46
- middleware: any[];
47
+ middleware?: any[];
47
48
  /**
48
49
  * controller middleware in this router
49
50
  */
50
- controllerMiddleware: any[];
51
+ controllerMiddleware?: any[];
51
52
  /**
52
53
  * request args metadata
53
54
  */
54
- requestMetadata: any[];
55
+ requestMetadata?: any[];
55
56
  /**
56
57
  * response data metadata
57
58
  */
58
- responseMetadata: any[];
59
+ responseMetadata?: any[];
59
60
  /**
60
61
  * serverless function name
61
62
  */
@@ -73,6 +74,7 @@ export interface RouterInfo {
73
74
  */
74
75
  functionMetadata?: any;
75
76
  }
77
+ export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'url' | 'prefix' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
76
78
  export interface RouterPriority {
77
79
  prefix: string;
78
80
  priority: number;
@@ -88,15 +90,27 @@ export interface RouterCollectorOptions {
88
90
  includeFunctionRouter?: boolean;
89
91
  globalPrefix?: string;
90
92
  }
91
- export declare class WebRouterCollector {
92
- protected readonly baseDir: string;
93
+ export declare class MidwayWebRouterService {
94
+ readonly options: RouterCollectorOptions;
93
95
  private isReady;
94
96
  protected routes: Map<string, RouterInfo[]>;
95
97
  private routesPriority;
96
- protected options: RouterCollectorOptions;
97
- constructor(baseDir?: string, options?: RouterCollectorOptions);
98
- protected analyze(): Promise<void>;
99
- protected collectRoute(module: any, functionMeta?: boolean): void;
98
+ constructor(options?: RouterCollectorOptions);
99
+ private analyze;
100
+ /**
101
+ * dynamically add a controller
102
+ * @param controllerClz
103
+ * @param controllerOption
104
+ * @param functionMeta
105
+ */
106
+ addController(controllerClz: any, controllerOption: ControllerOption, functionMeta?: boolean): void;
107
+ /**
108
+ * dynamically add a route to root prefix
109
+ * @param routerPath
110
+ * @param routerFunction
111
+ * @param routerInfoOption
112
+ */
113
+ addRouter(routerPath: string | RegExp, routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
100
114
  protected collectFunctionRoute(module: any, functionMeta?: boolean): void;
101
115
  sortRouter(urlMatchList: RouterInfo[]): {
102
116
  _pureRouter: string;
@@ -107,15 +121,15 @@ export declare class WebRouterCollector {
107
121
  /**
108
122
  * uuid
109
123
  */
110
- id: string;
124
+ id?: string;
111
125
  /**
112
126
  * router prefix from controller
113
127
  */
114
- prefix: string;
128
+ prefix?: string;
115
129
  /**
116
130
  * router alias name
117
131
  */
118
- routerName: string;
132
+ routerName?: string;
119
133
  /**
120
134
  * router path, without prefix
121
135
  */
@@ -127,40 +141,40 @@ export declare class WebRouterCollector {
127
141
  /**
128
142
  * invoke function method
129
143
  */
130
- method: string;
144
+ method: string | ((...args: any[]) => void);
131
145
  /**
132
146
  * router description
133
147
  */
134
- description: string;
135
- summary: string;
148
+ description?: string;
149
+ summary?: string;
136
150
  /**
137
151
  * router handler function key,for IoC container load
138
152
  */
139
- handlerName: string;
153
+ handlerName?: string;
140
154
  /**
141
155
  * serverless func load key
142
156
  */
143
- funcHandlerName: string;
157
+ funcHandlerName?: string;
144
158
  /**
145
159
  * controller provideId
146
160
  */
147
- controllerId: string;
161
+ controllerId?: string;
148
162
  /**
149
163
  * router middleware
150
164
  */
151
- middleware: any[];
165
+ middleware?: any[];
152
166
  /**
153
167
  * controller middleware in this router
154
168
  */
155
- controllerMiddleware: any[];
169
+ controllerMiddleware?: any[];
156
170
  /**
157
171
  * request args metadata
158
172
  */
159
- requestMetadata: any[];
173
+ requestMetadata?: any[];
160
174
  /**
161
175
  * response data metadata
162
176
  */
163
- responseMetadata: any[];
177
+ responseMetadata?: any[];
164
178
  /**
165
179
  * serverless function name
166
180
  */
@@ -183,4 +197,17 @@ export declare class WebRouterCollector {
183
197
  getFlattenRouterTable(): Promise<RouterInfo[]>;
184
198
  private checkDuplicateAndPush;
185
199
  }
186
- //# sourceMappingURL=webRouterCollector.d.ts.map
200
+ /**
201
+ * @deprecated use built-in MidwayWebRouterService first
202
+ */
203
+ export declare class WebRouterCollector {
204
+ private baseDir;
205
+ private options;
206
+ private proxy;
207
+ constructor(baseDir?: string, options?: RouterCollectorOptions);
208
+ protected init(): Promise<void>;
209
+ getRoutePriorityList(): Promise<RouterPriority[]>;
210
+ getRouterTable(): Promise<Map<string, RouterInfo[]>>;
211
+ getFlattenRouterTable(): Promise<RouterInfo[]>;
212
+ }
213
+ //# sourceMappingURL=webRouterService.d.ts.map