@midwayjs/core 3.0.0-beta.9 → 3.0.4-beta.1

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 (52) hide show
  1. package/dist/baseFramework.d.ts +2 -1
  2. package/dist/baseFramework.js +13 -10
  3. package/dist/common/applicationManager.d.ts +11 -0
  4. package/dist/common/applicationManager.js +70 -0
  5. package/dist/common/dataListener.d.ts +11 -0
  6. package/dist/common/dataListener.js +43 -0
  7. package/dist/common/fileDetector.js +1 -1
  8. package/dist/common/middlewareManager.js +2 -2
  9. package/dist/common/webGenerator.d.ts +3 -14
  10. package/dist/common/webGenerator.js +21 -33
  11. package/dist/common/webRouterCollector.js +3 -3
  12. package/dist/context/container.js +22 -11
  13. package/dist/context/managedResolverFactory.d.ts +1 -0
  14. package/dist/context/managedResolverFactory.js +20 -5
  15. package/dist/context/requestContainer.js +2 -0
  16. package/dist/definitions/functionDefinition.d.ts +1 -0
  17. package/dist/definitions/functionDefinition.js +1 -0
  18. package/dist/definitions/objectCreator.js +9 -8
  19. package/dist/definitions/objectDefinition.d.ts +1 -0
  20. package/dist/definitions/objectDefinition.js +1 -0
  21. package/dist/error/base.d.ts +22 -3
  22. package/dist/error/base.js +34 -5
  23. package/dist/error/framework.d.ts +27 -2
  24. package/dist/error/framework.js +51 -14
  25. package/dist/error/http.d.ts +146 -41
  26. package/dist/error/http.js +164 -31
  27. package/dist/error/index.d.ts +1 -1
  28. package/dist/error/index.js +4 -1
  29. package/dist/functional/configuration.d.ts +2 -0
  30. package/dist/functional/configuration.js +10 -0
  31. package/dist/index.d.ts +3 -0
  32. package/dist/index.js +5 -1
  33. package/dist/interface.d.ts +50 -28
  34. package/dist/service/aspectService.js +1 -1
  35. package/dist/service/configService.d.ts +3 -1
  36. package/dist/service/configService.js +23 -17
  37. package/dist/service/decoratorService.js +25 -13
  38. package/dist/service/environmentService.d.ts +1 -1
  39. package/dist/service/frameworkService.d.ts +3 -2
  40. package/dist/service/frameworkService.js +17 -12
  41. package/dist/service/lifeCycleService.js +5 -5
  42. package/dist/service/loggerService.d.ts +1 -1
  43. package/dist/service/middlewareService.d.ts +3 -4
  44. package/dist/service/middlewareService.js +7 -11
  45. package/dist/setup.js +8 -4
  46. package/dist/util/extend.d.ts +2 -0
  47. package/dist/util/extend.js +55 -0
  48. package/dist/util/webRouterParam.js +24 -4
  49. package/package.json +10 -12
  50. package/CHANGELOG.md +0 -2208
  51. package/dist/error/code.d.ts +0 -60
  52. package/dist/error/code.js +0 -65
@@ -72,7 +72,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
72
72
  * @deprecated
73
73
  */
74
74
  protected afterContainerReady(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
75
- getMiddleware<R, N>(lastMiddleware?: CommonMiddleware<CTX, R, N>): Promise<MiddlewareRespond<CTX, R, N>>;
75
+ applyMiddleware<R, N>(lastMiddleware?: CommonMiddleware<CTX, R, N>): Promise<MiddlewareRespond<CTX, R, N>>;
76
76
  getLogger(name?: string): ILogger;
77
77
  getCoreLogger(): ILogger;
78
78
  createLogger(name: string, option?: LoggerOptions): ILogger;
@@ -80,6 +80,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
80
80
  getFrameworkName(): string;
81
81
  getDefaultContextLoggerClass(): any;
82
82
  useMiddleware(Middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
83
+ getMiddleware(): ContextMiddlewareManager<CTX, ResOrNext, Next>;
83
84
  useFilter(Filter: CommonFilterUnion<CTX, ResOrNext, Next>): void;
84
85
  protected createMiddlewareManager(): ContextMiddlewareManager<CTX, ResOrNext, Next>;
85
86
  protected createFilterManager(): FilterManager<CTX, ResOrNext, Next>;
@@ -21,6 +21,8 @@ const loggerService_1 = require("./service/loggerService");
21
21
  const middlewareManager_1 = require("./common/middlewareManager");
22
22
  const middlewareService_1 = require("./service/middlewareService");
23
23
  const filterManager_1 = require("./common/filterManager");
24
+ const util = require("util");
25
+ const debug = util.debuglog('midway:debug');
24
26
  class BaseFramework {
25
27
  constructor(applicationContext) {
26
28
  this.applicationContext = applicationContext;
@@ -173,13 +175,13 @@ class BaseFramework {
173
175
  return this.getApplicationContext().getAttr(key);
174
176
  },
175
177
  useMiddleware: (middleware) => {
176
- this.middlewareManager.insertLast(middleware);
178
+ return this.useMiddleware(middleware);
177
179
  },
178
180
  getMiddleware: () => {
179
- return this.middlewareManager;
181
+ return this.getMiddleware();
180
182
  },
181
183
  useFilter: (Filter) => {
182
- this.filterManager.useFilter(Filter);
184
+ return this.useFilter(Filter);
183
185
  },
184
186
  };
185
187
  for (const method of whiteList) {
@@ -204,7 +206,7 @@ class BaseFramework {
204
206
  * @deprecated
205
207
  */
206
208
  async afterContainerReady(options) { }
207
- async getMiddleware(lastMiddleware) {
209
+ async applyMiddleware(lastMiddleware) {
208
210
  if (!this.composeMiddleware) {
209
211
  this.middlewareManager.insertFirst((async (ctx, next) => {
210
212
  let returnResult = undefined;
@@ -220,14 +222,12 @@ class BaseFramework {
220
222
  }
221
223
  return returnResult.result;
222
224
  }));
223
- this.composeMiddleware = await this.middlewareService.compose(this.middlewareManager);
225
+ debug(`[core]: Compose middleware = [${this.middlewareManager.getNames()}]`);
226
+ this.composeMiddleware = await this.middlewareService.compose(this.middlewareManager, this.app);
224
227
  await this.filterManager.init(this.applicationContext);
225
228
  }
226
229
  if (lastMiddleware) {
227
- return await this.middlewareService.compose([
228
- this.composeMiddleware,
229
- lastMiddleware,
230
- ]);
230
+ return await this.middlewareService.compose([this.composeMiddleware, lastMiddleware], this.app);
231
231
  }
232
232
  else {
233
233
  return this.composeMiddleware;
@@ -255,8 +255,11 @@ class BaseFramework {
255
255
  useMiddleware(Middleware) {
256
256
  this.middlewareManager.insertLast(Middleware);
257
257
  }
258
+ getMiddleware() {
259
+ return this.middlewareManager;
260
+ }
258
261
  useFilter(Filter) {
259
- this.filterManager.useFilter(Filter);
262
+ return this.filterManager.useFilter(Filter);
260
263
  }
261
264
  createMiddlewareManager() {
262
265
  return new middlewareManager_1.ContextMiddlewareManager();
@@ -0,0 +1,11 @@
1
+ import { IMidwayApplication, IMidwayFramework } from '../interface';
2
+ import { FrameworkType } from '@midwayjs/decorator';
3
+ export declare class MidwayApplicationManager {
4
+ private globalFrameworkMap;
5
+ private globalFrameworkTypeMap;
6
+ addFramework(namespace: any, framework: IMidwayFramework<any, any, any>): void;
7
+ getFramework(namespaceOrFrameworkType: string | FrameworkType): IMidwayFramework<any, any, any, unknown, unknown>;
8
+ getApplication(namespaceOrFrameworkType: string | FrameworkType): IMidwayApplication;
9
+ getApplications(namespaces?: Array<string | FrameworkType>): IMidwayApplication[];
10
+ }
11
+ //# sourceMappingURL=applicationManager.d.ts.map
@@ -0,0 +1,70 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.MidwayApplicationManager = void 0;
10
+ const decorator_1 = require("@midwayjs/decorator");
11
+ let MidwayApplicationManager = class MidwayApplicationManager {
12
+ constructor() {
13
+ this.globalFrameworkMap = new Map();
14
+ this.globalFrameworkTypeMap = new WeakMap();
15
+ }
16
+ addFramework(namespace, framework) {
17
+ this.globalFrameworkMap.set(namespace, framework);
18
+ this.globalFrameworkTypeMap.set(framework.getFrameworkType(), framework);
19
+ }
20
+ getFramework(namespaceOrFrameworkType) {
21
+ if (typeof namespaceOrFrameworkType === 'string') {
22
+ if (this.globalFrameworkMap.has(namespaceOrFrameworkType)) {
23
+ return this.globalFrameworkMap.get(namespaceOrFrameworkType);
24
+ }
25
+ }
26
+ else {
27
+ if (this.globalFrameworkTypeMap.has(namespaceOrFrameworkType)) {
28
+ return this.globalFrameworkTypeMap.get(namespaceOrFrameworkType);
29
+ }
30
+ }
31
+ }
32
+ getApplication(namespaceOrFrameworkType) {
33
+ if (typeof namespaceOrFrameworkType === 'string') {
34
+ if (this.globalFrameworkMap.has(namespaceOrFrameworkType)) {
35
+ return this.globalFrameworkMap
36
+ .get(namespaceOrFrameworkType)
37
+ .getApplication();
38
+ }
39
+ }
40
+ else {
41
+ if (this.globalFrameworkTypeMap.has(namespaceOrFrameworkType)) {
42
+ return this.globalFrameworkTypeMap
43
+ .get(namespaceOrFrameworkType)
44
+ .getApplication();
45
+ }
46
+ }
47
+ }
48
+ getApplications(namespaces) {
49
+ if (!namespaces) {
50
+ return Array.from(this.globalFrameworkMap.values()).map(framework => {
51
+ return framework.getApplication();
52
+ });
53
+ }
54
+ else {
55
+ return namespaces
56
+ .map(namespace => {
57
+ return this.getApplication(namespace);
58
+ })
59
+ .filter(app => {
60
+ return !!app;
61
+ });
62
+ }
63
+ }
64
+ };
65
+ MidwayApplicationManager = __decorate([
66
+ (0, decorator_1.Provide)(),
67
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton)
68
+ ], MidwayApplicationManager);
69
+ exports.MidwayApplicationManager = MidwayApplicationManager;
70
+ //# sourceMappingURL=applicationManager.js.map
@@ -0,0 +1,11 @@
1
+ export declare abstract class DataListener<T> {
2
+ private innerData;
3
+ protected init(): Promise<void>;
4
+ abstract initData(): T;
5
+ abstract onData(callback: (data: T) => void): any;
6
+ protected setData(data: T): void;
7
+ getData(): T;
8
+ stop(): Promise<void>;
9
+ protected destroyListener(): Promise<void>;
10
+ }
11
+ //# sourceMappingURL=dataListener.d.ts.map
@@ -0,0 +1,43 @@
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.DataListener = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ class DataListener {
15
+ async init() {
16
+ this.innerData = await this.initData();
17
+ await this.onData(this.setData.bind(this));
18
+ }
19
+ setData(data) {
20
+ this.innerData = data;
21
+ }
22
+ getData() {
23
+ return this.innerData;
24
+ }
25
+ async stop() {
26
+ await this.destroyListener();
27
+ }
28
+ async destroyListener() { }
29
+ }
30
+ __decorate([
31
+ (0, decorator_1.Init)(),
32
+ __metadata("design:type", Function),
33
+ __metadata("design:paramtypes", []),
34
+ __metadata("design:returntype", Promise)
35
+ ], DataListener.prototype, "init", null);
36
+ __decorate([
37
+ (0, decorator_1.Destroy)(),
38
+ __metadata("design:type", Function),
39
+ __metadata("design:paramtypes", []),
40
+ __metadata("design:returntype", Promise)
41
+ ], DataListener.prototype, "stop", null);
42
+ exports.DataListener = DataListener;
43
+ //# sourceMappingURL=dataListener.js.map
@@ -47,7 +47,7 @@ class DirectoryFileDetector extends AbstractFileDetector {
47
47
  continue;
48
48
  }
49
49
  }
50
- else if ((0, decorator_1.isRegExp)(resolveFilter.pattern)) {
50
+ else if (decorator_1.Types.isRegExp(resolveFilter.pattern)) {
51
51
  if (resolveFilter.pattern.test(file)) {
52
52
  const exports = resolveFilter.ignoreRequire
53
53
  ? undefined
@@ -151,8 +151,8 @@ class ContextMiddlewareManager extends Array {
151
151
  * @param middleware
152
152
  */
153
153
  getMiddlewareName(middleware) {
154
- var _a;
155
- return (_a = middleware._name) !== null && _a !== void 0 ? _a : middleware.name;
154
+ var _a, _b;
155
+ return ((_b = (_a = (middleware.getName && middleware.getName())) !== null && _a !== void 0 ? _a : middleware._name) !== null && _b !== void 0 ? _b : middleware.name);
156
156
  }
157
157
  /**
158
158
  * remove a middleware
@@ -1,19 +1,9 @@
1
- /**
2
- * wrap controller string to middleware function
3
- * @param controllerMapping like FooController.index
4
- * @param routeArgsInfo
5
- * @param routerResponseData
6
- */
7
- import { MidwayFrameworkType } from '@midwayjs/decorator';
8
- import { IMidwayContainer, RouterInfo } from '../index';
9
- import { ILogger } from '@midwayjs/logger';
1
+ import { RouterInfo, IMidwayApplication } from '../index';
10
2
  export declare abstract class WebControllerGenerator<Router extends {
11
3
  use: (...args: any[]) => void;
12
4
  }> {
13
- readonly applicationContext: IMidwayContainer;
14
- readonly frameworkType: MidwayFrameworkType;
15
- readonly logger?: ILogger;
16
- protected constructor(applicationContext: IMidwayContainer, frameworkType: MidwayFrameworkType, logger?: ILogger);
5
+ readonly app: IMidwayApplication;
6
+ protected constructor(app: IMidwayApplication);
17
7
  /**
18
8
  * wrap controller string to middleware function
19
9
  * @param routeInfo
@@ -22,6 +12,5 @@ export declare abstract class WebControllerGenerator<Router extends {
22
12
  loadMidwayController(globalPrefix: string, routerHandler?: (newRouter: Router) => void): Promise<void>;
23
13
  abstract createRouter(routerOptions: any): Router;
24
14
  abstract generateController(routeInfo: RouterInfo): any;
25
- protected handlerWebMiddleware(middlewares: any[], handlerCallback: (middlewareImpl: any) => void): Promise<void>;
26
15
  }
27
16
  //# sourceMappingURL=webGenerator.d.ts.map
@@ -12,10 +12,8 @@ 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(applicationContext, frameworkType, logger) {
16
- this.applicationContext = applicationContext;
17
- this.frameworkType = frameworkType;
18
- this.logger = logger;
15
+ constructor(app) {
16
+ this.app = app;
19
17
  }
20
18
  /**
21
19
  * wrap controller string to middleware function
@@ -65,30 +63,36 @@ class WebControllerGenerator {
65
63
  });
66
64
  const routerTable = await collector.getRouterTable();
67
65
  const routerList = await collector.getRoutePriorityList();
66
+ const applicationContext = this.app.getApplicationContext();
67
+ const logger = this.app.getCoreLogger();
68
+ const middlewareService = applicationContext.get(index_1.MidwayMiddlewareService);
68
69
  for (const routerInfo of routerList) {
69
70
  // bind controller first
70
- this.applicationContext.bindClass(routerInfo.routerModule);
71
- (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
72
- debug(`[core:webGenerator]: Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
71
+ applicationContext.bindClass(routerInfo.routerModule);
72
+ logger.debug(`Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
73
+ debug(`[core]: Load Controller "${routerInfo.controllerId}", prefix=${routerInfo.prefix}`);
73
74
  // new router
74
75
  const newRouter = this.createRouter({
75
76
  prefix: routerInfo.prefix,
76
77
  ...routerInfo.routerOptions,
77
78
  });
78
79
  // add router middleware
79
- await this.handlerWebMiddleware(routerInfo.middleware, middlewareImpl => {
80
- newRouter.use(middlewareImpl);
81
- });
80
+ routerInfo.middleware = (_a = routerInfo.middleware) !== null && _a !== void 0 ? _a : [];
81
+ if (routerInfo.middleware.length) {
82
+ const routerMiddlewareFn = await middlewareService.compose(routerInfo.middleware, this.app);
83
+ newRouter.use(routerMiddlewareFn);
84
+ }
82
85
  // add route
83
86
  const routes = routerTable.get(routerInfo.prefix);
84
87
  for (const routeInfo of routes) {
85
88
  // get middleware
86
- const middlewares2 = routeInfo.middleware;
87
89
  const methodMiddlewares = [];
88
- await this.handlerWebMiddleware(middlewares2, middlewareImpl => {
89
- methodMiddlewares.push(middlewareImpl);
90
- });
91
- if (this.frameworkType === decorator_1.MidwayFrameworkType.WEB_KOA) {
90
+ routeInfo.middleware = (_b = routeInfo.middleware) !== null && _b !== void 0 ? _b : [];
91
+ if (routeInfo.middleware.length) {
92
+ const routeMiddlewareFn = await middlewareService.compose(routeInfo.middleware, this.app);
93
+ methodMiddlewares.push(routeMiddlewareFn);
94
+ }
95
+ if (this.app.getFrameworkType() === decorator_1.MidwayFrameworkType.WEB_KOA) {
92
96
  if (typeof routeInfo.url === 'string' && /\*$/.test(routeInfo.url)) {
93
97
  routeInfo.url = routeInfo.url.replace('*', '(.*)');
94
98
  }
@@ -99,8 +103,8 @@ class WebControllerGenerator {
99
103
  ...methodMiddlewares,
100
104
  this.generateController(routeInfo),
101
105
  ];
102
- (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
103
- debug(`[core:webGenerator]: Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
106
+ logger.debug(`Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
107
+ debug(`[core]: Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
104
108
  // apply controller from request context
105
109
  // eslint-disable-next-line prefer-spread
106
110
  newRouter[routeInfo.requestMethod].apply(newRouter, routerArgs);
@@ -108,22 +112,6 @@ class WebControllerGenerator {
108
112
  routerHandler && routerHandler(newRouter);
109
113
  }
110
114
  }
111
- async handlerWebMiddleware(middlewares, handlerCallback) {
112
- if (middlewares && middlewares.length) {
113
- for (const middleware of middlewares) {
114
- if (typeof middleware === 'function') {
115
- // web function middleware
116
- handlerCallback(middleware);
117
- }
118
- else {
119
- const middlewareImpl = await this.applicationContext.getAsync(middleware);
120
- if (middlewareImpl && typeof middlewareImpl.resolve === 'function') {
121
- handlerCallback(middlewareImpl.resolve());
122
- }
123
- }
124
- }
125
- }
126
- }
127
115
  }
128
116
  exports.WebControllerGenerator = WebControllerGenerator;
129
117
  //# sourceMappingURL=webGenerator.js.map
@@ -58,7 +58,7 @@ class WebRouterCollector {
58
58
  collectRoute(module, functionMeta = false) {
59
59
  var _a;
60
60
  const controllerId = (0, decorator_1.getProviderName)(module);
61
- debug(`[core:webCollector]: Found Controller ${controllerId}.`);
61
+ debug(`[core]: Found Controller ${controllerId}.`);
62
62
  const id = (0, decorator_1.getProviderUUId)(module);
63
63
  const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
64
64
  let priority;
@@ -232,7 +232,7 @@ class WebRouterCollector {
232
232
  return urlMatchList
233
233
  .map(item => {
234
234
  const urlString = item.url.toString();
235
- const weightArr = (0, decorator_1.isRegExp)(item.url)
235
+ const weightArr = decorator_1.Types.isRegExp(item.url)
236
236
  ? urlString.split('\\/')
237
237
  : urlString.split('/');
238
238
  let weight = 0;
@@ -319,7 +319,7 @@ class WebRouterCollector {
319
319
  item.requestMethod === routerInfo.requestMethod);
320
320
  });
321
321
  if (matched && matched.length) {
322
- throw new Error(`Duplicate router "${routerInfo.requestMethod} ${routerInfo.url}" at "${matched[0].handlerName}" and "${routerInfo.handlerName}"`);
322
+ throw new error_1.MidwayDuplicateRouteError(`${routerInfo.requestMethod} ${routerInfo.url}`, `${matched[0].handlerName}`, `${routerInfo.handlerName}`);
323
323
  }
324
324
  prefixList.push(routerInfo);
325
325
  }
@@ -144,16 +144,16 @@ class ContainerConfiguration {
144
144
  }
145
145
  getConfigurationExport(exports) {
146
146
  const mods = [];
147
- if ((0, decorator_1.isClass)(exports) ||
148
- (0, decorator_1.isFunction)(exports) ||
147
+ if (decorator_1.Types.isClass(exports) ||
148
+ decorator_1.Types.isFunction(exports) ||
149
149
  exports instanceof configuration_1.FunctionalConfiguration) {
150
150
  mods.push(exports);
151
151
  }
152
152
  else {
153
153
  for (const m in exports) {
154
154
  const module = exports[m];
155
- if ((0, decorator_1.isClass)(module) ||
156
- (0, decorator_1.isFunction)(module) ||
155
+ if (decorator_1.Types.isClass(module) ||
156
+ decorator_1.Types.isFunction(module) ||
157
157
  module instanceof configuration_1.FunctionalConfiguration) {
158
158
  mods.push(module);
159
159
  }
@@ -228,6 +228,7 @@ class MidwayContainer {
228
228
  configuration.load(module);
229
229
  for (const ns of configuration.getNamespaceList()) {
230
230
  this.namespaceSet.add(ns);
231
+ debug(`[core]: load configuration in namespace="${ns} complete"`);
231
232
  }
232
233
  }
233
234
  }
@@ -240,13 +241,13 @@ class MidwayContainer {
240
241
  (_a = this.fileDetector) === null || _a === void 0 ? void 0 : _a.run(this);
241
242
  }
242
243
  bindClass(exports, options) {
243
- if ((0, decorator_1.isClass)(exports) || (0, decorator_1.isFunction)(exports)) {
244
+ if (decorator_1.Types.isClass(exports) || decorator_1.Types.isFunction(exports)) {
244
245
  this.bindModule(exports, options);
245
246
  }
246
247
  else {
247
248
  for (const m in exports) {
248
249
  const module = exports[m];
249
- if ((0, decorator_1.isClass)(module) || (0, decorator_1.isFunction)(module)) {
250
+ if (decorator_1.Types.isClass(module) || decorator_1.Types.isFunction(module)) {
250
251
  this.bindModule(module, options);
251
252
  }
252
253
  }
@@ -254,7 +255,7 @@ class MidwayContainer {
254
255
  }
255
256
  bind(identifier, target, options) {
256
257
  var _a;
257
- if ((0, decorator_1.isClass)(identifier) || (0, decorator_1.isFunction)(identifier)) {
258
+ if (decorator_1.Types.isClass(identifier) || decorator_1.Types.isFunction(identifier)) {
258
259
  return this.bindModule(identifier, target);
259
260
  }
260
261
  if (this.registry.hasDefinition(identifier)) {
@@ -262,13 +263,13 @@ class MidwayContainer {
262
263
  return;
263
264
  }
264
265
  let definition;
265
- if ((0, decorator_1.isClass)(target)) {
266
+ if (decorator_1.Types.isClass(target)) {
266
267
  definition = new objectDefinition_1.ObjectDefinition();
267
268
  definition.name = (0, decorator_1.getProviderName)(target);
268
269
  }
269
270
  else {
270
271
  definition = new functionDefinition_1.FunctionDefinition();
271
- if (!(0, decorator_1.isAsyncFunction)(target)) {
272
+ if (!decorator_1.Types.isAsyncFunction(target)) {
272
273
  definition.asynchronous = false;
273
274
  }
274
275
  definition.name = definition.id;
@@ -315,6 +316,10 @@ class MidwayContainer {
315
316
  debugBind(` register scope = ${objDefOptions.scope}`);
316
317
  definition.scope = objDefOptions.scope;
317
318
  }
319
+ if (objDefOptions.allowDowngrade) {
320
+ debugBind(` register allowDowngrade = ${objDefOptions.allowDowngrade}`);
321
+ definition.allowDowngrade = objDefOptions.allowDowngrade;
322
+ }
318
323
  this.objectCreateEventTarget.emit(interface_1.ObjectLifeCycleEvent.BEFORE_BIND, target, {
319
324
  context: this,
320
325
  definition,
@@ -327,7 +332,7 @@ class MidwayContainer {
327
332
  }
328
333
  }
329
334
  bindModule(module, options) {
330
- if ((0, decorator_1.isClass)(module)) {
335
+ if (decorator_1.Types.isClass(module)) {
331
336
  const providerId = (0, decorator_1.getProviderUUId)(module);
332
337
  if (providerId) {
333
338
  this.identifierMapping.saveClassRelation(module, options === null || options === void 0 ? void 0 : options.namespace);
@@ -343,7 +348,7 @@ class MidwayContainer {
343
348
  if (!info.scope) {
344
349
  info.scope = decorator_1.ScopeEnum.Request;
345
350
  }
346
- const uuid = (0, decorator_1.generateRandomId)();
351
+ const uuid = decorator_1.Utils.generateRandomId();
347
352
  this.identifierMapping.saveFunctionRelation(info.id, uuid);
348
353
  this.bind(uuid, module, {
349
354
  scope: info.scope,
@@ -384,7 +389,10 @@ class MidwayContainer {
384
389
  }
385
390
  get(identifier, args, objectContext) {
386
391
  var _a;
392
+ args = args !== null && args !== void 0 ? args : [];
393
+ objectContext = objectContext !== null && objectContext !== void 0 ? objectContext : { originName: identifier };
387
394
  if (typeof identifier !== 'string') {
395
+ objectContext.originName = identifier.name;
388
396
  identifier = this.getIdentifier(identifier);
389
397
  }
390
398
  if (this.registry.hasObject(identifier)) {
@@ -401,7 +409,10 @@ class MidwayContainer {
401
409
  }
402
410
  async getAsync(identifier, args, objectContext) {
403
411
  var _a;
412
+ args = args !== null && args !== void 0 ? args : [];
413
+ objectContext = objectContext !== null && objectContext !== void 0 ? objectContext : { originName: identifier };
404
414
  if (typeof identifier !== 'string') {
415
+ objectContext.originName = identifier.name;
405
416
  identifier = this.getIdentifier(identifier);
406
417
  }
407
418
  if (this.registry.hasObject(identifier)) {
@@ -52,5 +52,6 @@ export declare class ManagedResolverFactory {
52
52
  */
53
53
  depthFirstSearch(identifier: string, definition: IObjectDefinition, depth?: string[]): boolean;
54
54
  private getObjectEventTarget;
55
+ private checkSingletonInvokeRequest;
55
56
  }
56
57
  //# sourceMappingURL=managedResolverFactory.d.ts.map
@@ -56,14 +56,14 @@ class ManagedResolverFactory {
56
56
  resolveManaged(managed, originPropertyName) {
57
57
  const resolver = this.resolvers[managed.type];
58
58
  if (!resolver || resolver.type !== managed.type) {
59
- throw new Error(`${managed.type} resolver is not exists!`);
59
+ throw new error_1.MidwayResolverMissingError(managed.type);
60
60
  }
61
61
  return resolver.resolve(managed, originPropertyName);
62
62
  }
63
63
  async resolveManagedAsync(managed, originPropertyName) {
64
64
  const resolver = this.resolvers[managed.type];
65
65
  if (!resolver || resolver.type !== managed.type) {
66
- throw new Error(`${managed.type} resolver is not exists!`);
66
+ throw new error_1.MidwayResolverMissingError(managed.type);
67
67
  }
68
68
  return resolver.resolveAsync(managed, originPropertyName);
69
69
  }
@@ -89,7 +89,7 @@ class ManagedResolverFactory {
89
89
  this.context.get(dep, args);
90
90
  }
91
91
  }
92
- debugLog(`[core:container]: Create id = "${definition.name}" ${definition.id}.`);
92
+ debugLog(`[core]: Create id = "${definition.name}" ${definition.id}.`);
93
93
  const Clzz = definition.creator.load();
94
94
  let constructorArgs = [];
95
95
  if (args && Array.isArray(args) && args.length > 0) {
@@ -113,6 +113,7 @@ class ManagedResolverFactory {
113
113
  if (definition.properties) {
114
114
  const keys = definition.properties.propertyKeys();
115
115
  for (const key of keys) {
116
+ this.checkSingletonInvokeRequest(definition, key);
116
117
  try {
117
118
  inst[key] = this.resolveManaged(definition.properties.get(key), key);
118
119
  }
@@ -174,7 +175,7 @@ class ManagedResolverFactory {
174
175
  await this.context.getAsync(dep, args);
175
176
  }
176
177
  }
177
- debugLog(`[core:container]: Create id = "${definition.name}" ${definition.id}.`);
178
+ debugLog(`[core]: Create id = "${definition.name}" ${definition.id}.`);
178
179
  const Clzz = definition.creator.load();
179
180
  let constructorArgs = [];
180
181
  if (args && Array.isArray(args) && args.length > 0) {
@@ -187,7 +188,7 @@ class ManagedResolverFactory {
187
188
  inst = await definition.creator.doConstructAsync(Clzz, constructorArgs, this.context);
188
189
  if (!inst) {
189
190
  this.removeCreateStatus(definition, false);
190
- throw new Error(`${definition.id} construct return undefined`);
191
+ throw new error_1.MidwayCommonError(`${definition.id} construct return undefined`);
191
192
  }
192
193
  // binding ctx object
193
194
  if (definition.isRequestScope() &&
@@ -202,6 +203,7 @@ class ManagedResolverFactory {
202
203
  if (definition.properties) {
203
204
  const keys = definition.properties.propertyKeys();
204
205
  for (const key of keys) {
206
+ this.checkSingletonInvokeRequest(definition, key);
205
207
  try {
206
208
  inst[key] = await this.resolveManagedAsync(definition.properties.get(key), key);
207
209
  }
@@ -371,6 +373,19 @@ class ManagedResolverFactory {
371
373
  }
372
374
  return this.context.objectCreateEventTarget;
373
375
  }
376
+ checkSingletonInvokeRequest(definition, key) {
377
+ if (definition.isSingletonScope()) {
378
+ const managedRef = definition.properties.get(key);
379
+ if (this.context.hasDefinition(managedRef === null || managedRef === void 0 ? void 0 : managedRef.name)) {
380
+ const propertyDefinition = this.context.registry.getDefinition(managedRef.name);
381
+ if (propertyDefinition.isRequestScope() &&
382
+ !propertyDefinition.allowDowngrade) {
383
+ throw new error_1.MidwaySingletonInjectRequestError(definition.path.name, propertyDefinition.path.name);
384
+ }
385
+ }
386
+ }
387
+ return true;
388
+ }
374
389
  }
375
390
  exports.ManagedResolverFactory = ManagedResolverFactory;
376
391
  //# sourceMappingURL=managedResolverFactory.js.map
@@ -13,6 +13,8 @@ class MidwayRequestContainer extends container_1.MidwayContainer {
13
13
  this.ctx = ctx;
14
14
  // register ctx
15
15
  this.registerObject(interface_1.REQUEST_CTX_KEY, ctx);
16
+ // register res
17
+ this.registerObject('res', {});
16
18
  if (ctx.logger) {
17
19
  // register contextLogger
18
20
  this.registerObject('logger', ctx.logger);
@@ -18,6 +18,7 @@ export declare class FunctionDefinition implements IObjectDefinition {
18
18
  asynchronous: boolean;
19
19
  handlerProps: any[];
20
20
  createFrom: any;
21
+ allowDowngrade: boolean;
21
22
  protected innerAutowire: boolean;
22
23
  protected innerScope: ScopeEnum;
23
24
  getAttr(key: ObjectIdentifier): any;
@@ -23,6 +23,7 @@ class FunctionDefinition {
23
23
  this.namespace = '';
24
24
  this.asynchronous = true;
25
25
  this.handlerProps = [];
26
+ this.allowDowngrade = false;
26
27
  // 函数工厂创建的对象默认不需要自动装配
27
28
  this.innerAutowire = false;
28
29
  this.innerScope = decorator_1.ScopeEnum.Singleton;