@midwayjs/core 3.0.0-alpha.9 → 3.0.0-beta.4

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 (109) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/baseFramework.d.ts +55 -22
  3. package/dist/baseFramework.js +151 -232
  4. package/dist/{util → common}/fileDetector.d.ts +0 -0
  5. package/dist/{util → common}/fileDetector.js +16 -10
  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/common/middlewareManager.js +48 -0
  10. package/dist/common/serviceFactory.d.ts +15 -0
  11. package/dist/{util → common}/serviceFactory.js +16 -6
  12. package/dist/{util → common}/triggerCollector.d.ts +0 -0
  13. package/dist/{util → common}/triggerCollector.js +0 -0
  14. package/dist/common/webGenerator.d.ts +27 -0
  15. package/dist/common/webGenerator.js +125 -0
  16. package/dist/{util → common}/webRouterCollector.d.ts +21 -2
  17. package/dist/{util → common}/webRouterCollector.js +115 -138
  18. package/dist/config/config.default.d.ts +7 -0
  19. package/dist/config/config.default.js +28 -0
  20. package/dist/context/container.d.ts +73 -43
  21. package/dist/context/container.js +277 -270
  22. package/dist/context/definitionRegistry.d.ts +26 -0
  23. package/dist/context/definitionRegistry.js +124 -0
  24. package/dist/context/managedResolverFactory.d.ts +15 -32
  25. package/dist/context/managedResolverFactory.js +88 -317
  26. package/dist/context/providerWrapper.d.ts +2 -3
  27. package/dist/context/requestContainer.d.ts +0 -2
  28. package/dist/context/requestContainer.js +9 -26
  29. package/dist/definitions/functionDefinition.d.ts +3 -4
  30. package/dist/definitions/functionDefinition.js +0 -6
  31. package/dist/definitions/objectCreator.js +6 -6
  32. package/dist/definitions/objectDefinition.d.ts +4 -6
  33. package/dist/definitions/objectDefinition.js +0 -8
  34. package/dist/definitions/properties.d.ts +2 -15
  35. package/dist/definitions/properties.js +3 -72
  36. package/dist/error/base.d.ts +13 -0
  37. package/dist/error/base.js +19 -0
  38. package/dist/error/code.d.ts +59 -0
  39. package/dist/error/code.js +64 -0
  40. package/dist/error/framework.d.ts +21 -0
  41. package/dist/error/framework.js +52 -0
  42. package/dist/error/http.d.ts +58 -0
  43. package/dist/error/http.js +82 -0
  44. package/dist/error/index.d.ts +4 -0
  45. package/dist/error/index.js +16 -0
  46. package/dist/functional/configuration.d.ts +4 -2
  47. package/dist/functional/configuration.js +12 -2
  48. package/dist/index.d.ts +23 -10
  49. package/dist/index.js +33 -33
  50. package/dist/interface.d.ts +263 -184
  51. package/dist/interface.js +9 -1
  52. package/dist/service/aspectService.d.ts +11 -14
  53. package/dist/service/aspectService.js +116 -172
  54. package/dist/service/configService.d.ts +10 -8
  55. package/dist/service/configService.js +61 -38
  56. package/dist/service/decoratorService.d.ts +23 -0
  57. package/dist/service/decoratorService.js +149 -0
  58. package/dist/service/environmentService.js +15 -4
  59. package/dist/service/frameworkService.d.ts +25 -0
  60. package/dist/service/frameworkService.js +171 -0
  61. package/dist/service/informationService.d.ts +4 -7
  62. package/dist/service/informationService.js +41 -10
  63. package/dist/service/lifeCycleService.d.ts +14 -0
  64. package/dist/service/lifeCycleService.js +130 -0
  65. package/dist/service/loggerService.d.ts +27 -0
  66. package/dist/service/loggerService.js +132 -0
  67. package/dist/service/middlewareService.d.ts +11 -0
  68. package/dist/service/middlewareService.js +119 -0
  69. package/dist/{features/pipeline.d.ts → service/pipelineService.d.ts} +56 -46
  70. package/dist/{features/pipeline.js → service/pipelineService.js} +54 -19
  71. package/dist/setup.d.ts +4 -0
  72. package/dist/setup.js +113 -0
  73. package/dist/util/contextUtil.d.ts +1 -1
  74. package/dist/util/contextUtil.js +2 -2
  75. package/dist/util/index.d.ts +55 -0
  76. package/dist/util/index.js +137 -7
  77. package/dist/util/pathFileUtil.js +2 -2
  78. package/dist/util/pathToRegexp.d.ts +17 -0
  79. package/dist/util/pathToRegexp.js +280 -0
  80. package/dist/util/webRouterParam.d.ts +2 -2
  81. package/dist/util/webRouterParam.js +19 -20
  82. package/package.json +8 -13
  83. package/dist/common/lodashWrap.d.ts +0 -9
  84. package/dist/common/lodashWrap.js +0 -18
  85. package/dist/common/notFoundError.d.ts +0 -8
  86. package/dist/common/notFoundError.js +0 -20
  87. package/dist/common/reflectTool.d.ts +0 -15
  88. package/dist/common/reflectTool.js +0 -83
  89. package/dist/context/applicationContext.d.ts +0 -81
  90. package/dist/context/applicationContext.js +0 -263
  91. package/dist/context/managed.d.ts +0 -45
  92. package/dist/context/managed.js +0 -69
  93. package/dist/context/resolverHandler.d.ts +0 -34
  94. package/dist/context/resolverHandler.js +0 -88
  95. package/dist/definitions/messageSource.d.ts +0 -13
  96. package/dist/definitions/messageSource.js +0 -74
  97. package/dist/definitions/resource.d.ts +0 -27
  98. package/dist/definitions/resource.js +0 -116
  99. package/dist/features/index.d.ts +0 -2
  100. package/dist/features/index.js +0 -3
  101. package/dist/logger.d.ts +0 -4
  102. package/dist/logger.js +0 -20
  103. package/dist/util/containerUtil.d.ts +0 -11
  104. package/dist/util/containerUtil.js +0 -26
  105. package/dist/util/emptyFramework.d.ts +0 -62
  106. package/dist/util/emptyFramework.js +0 -72
  107. package/dist/util/serviceFactory.d.ts +0 -13
  108. package/dist/util/staticConfig.d.ts +0 -10
  109. package/dist/util/staticConfig.js +0 -67
@@ -1,166 +1,85 @@
1
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.BaseFramework = void 0;
4
13
  const interface_1 = require("./interface");
5
14
  const decorator_1 = require("@midwayjs/decorator");
6
15
  const logger_1 = require("@midwayjs/logger");
7
- const logger_2 = require("./logger");
8
16
  const requestContainer_1 = require("./context/requestContainer");
9
- const configuration_1 = require("./functional/configuration");
17
+ const environmentService_1 = require("./service/environmentService");
18
+ const configService_1 = require("./service/configService");
10
19
  const informationService_1 = require("./service/informationService");
11
- const containerUtil_1 = require("./util/containerUtil");
20
+ const loggerService_1 = require("./service/loggerService");
21
+ const middlewareManager_1 = require("./common/middlewareManager");
22
+ const middlewareService_1 = require("./service/middlewareService");
23
+ const filterManager_1 = require("./common/filterManager");
12
24
  class BaseFramework {
13
- constructor() {
25
+ constructor(applicationContext) {
26
+ this.applicationContext = applicationContext;
14
27
  this.defaultContext = {};
28
+ this.middlewareManager = this.createMiddlewareManager();
29
+ this.filterManager = this.createFilterManager();
30
+ this.composeMiddleware = null;
15
31
  }
16
- configure(options) {
17
- this.configurationOptions = options || {};
32
+ async init() {
33
+ var _a, _b, _c;
34
+ this.configurationOptions = (_a = this.configure()) !== null && _a !== void 0 ? _a : {};
18
35
  this.BaseContextLoggerClass =
19
- this.configurationOptions.ContextLoggerClass ||
20
- this.getDefaultContextLoggerClass();
21
- this.logger = this.configurationOptions.logger;
22
- this.appLogger = this.configurationOptions.appLogger;
36
+ (_b = this.configurationOptions.ContextLoggerClass) !== null && _b !== void 0 ? _b : this.getDefaultContextLoggerClass();
37
+ this.ContextLoggerApplyLogger =
38
+ (_c = this.configurationOptions.ContextLoggerApplyLogger) !== null && _c !== void 0 ? _c : 'appLogger';
39
+ this.logger = this.loggerService.getLogger('coreLogger');
40
+ this.appLogger = this.loggerService.getLogger('appLogger');
23
41
  return this;
24
42
  }
43
+ isEnable() {
44
+ return true;
45
+ }
25
46
  async initialize(options) {
26
- this.isMainFramework = options.isMainFramework;
27
- this.configurationOptions = this.configurationOptions || {};
28
- /**
29
- * before create MidwayContainer instance,can change init parameters
30
- */
31
47
  await this.beforeContainerInitialize(options);
32
- /**
33
- * initialize MidwayContainer instance
34
- */
35
48
  await this.containerInitialize(options);
36
- /**
37
- * before container load directory and bind
38
- */
39
49
  await this.afterContainerInitialize(options);
40
- /**
41
- * run container loadDirectoryLoad method to create object definition
42
- */
43
50
  await this.containerDirectoryLoad(options);
44
- /**
45
- * after container load directory and bind
46
- */
47
51
  await this.afterContainerDirectoryLoad(options);
48
52
  /**
49
53
  * Third party application initialization
50
54
  */
51
55
  await this.applicationInitialize(options);
52
- /**
53
- * start container ready
54
- */
55
56
  await this.containerReady(options);
56
- if (this.isMainFramework !== undefined) {
57
- // 多框架场景,由 bootstrap 执行后续流程
58
- return;
59
- }
60
- /**
61
- * load extensions and lifeCycle
62
- */
63
- await this.loadExtension();
64
- /**
65
- * after container refresh
66
- */
67
57
  await this.afterContainerReady(options);
68
58
  }
69
- async initializeInfo(options) {
70
- if (!this.applicationContext.getInformationService()) {
71
- const informationService = new informationService_1.MidwayInformationService(options);
72
- this.applicationContext.setInformationService(informationService);
73
- }
74
- }
75
- async initializeLogger(options) {
76
- if (!this.logger) {
77
- this.logger = new Proxy(logger_2.createMidwayLogger(this, 'coreLogger'), {});
78
- this.logger.updateDefaultLabel(this.getFrameworkName());
79
- }
80
- if (!this.appLogger) {
81
- this.appLogger = logger_2.createMidwayLogger(this, 'logger', {
82
- fileLogName: 'midway-app.log',
83
- });
84
- }
85
- }
86
- async containerInitialize(options) {
87
- /**
88
- * initialize container
89
- */
90
- if (options.applicationContext) {
91
- this.applicationContext = options.applicationContext;
92
- }
93
- else {
94
- this.applicationContext = containerUtil_1.createDirectoryGlobContainer({
95
- baseDir: options.baseDir,
96
- });
97
- }
98
- this.applicationContext.registerObject('baseDir', options.baseDir);
99
- this.applicationContext.registerObject('appDir', options.appDir);
100
- /**
101
- * initialize base information
102
- */
103
- await this.initializeInfo(options);
104
- /**
105
- * initialize framework logger
106
- */
107
- await this.initializeLogger(options);
108
- }
109
- async containerDirectoryLoad(options) {
110
- if (options.applicationContext) {
111
- // 如果有传入全局容器,就不需要再次扫描了
112
- return;
113
- }
114
- // 废弃 deprecated
115
- if (options.preloadModules && options.preloadModules.length) {
116
- for (const preloadModule of options.preloadModules) {
117
- this.applicationContext.bindClass(preloadModule);
118
- }
119
- }
120
- // register app
121
- this.applicationContext.registerDataHandler(decorator_1.APPLICATION_KEY, (key, meta) => {
122
- var _a;
123
- if (options.globalApplicationHandler) {
124
- return ((_a = options.globalApplicationHandler(meta === null || meta === void 0 ? void 0 : meta.type)) !== null && _a !== void 0 ? _a : this.getApplication());
125
- }
126
- else {
127
- return this.getApplication();
128
- }
129
- });
130
- // register logger
131
- this.getApplicationContext().registerDataHandler(decorator_1.LOGGER_KEY, key => {
132
- return this.getLogger(key);
133
- });
134
- }
59
+ /**
60
+ * @deprecated
61
+ */
62
+ async containerInitialize(options) { }
63
+ /**
64
+ * @deprecated
65
+ */
66
+ async containerDirectoryLoad(options) { }
67
+ /**
68
+ * @deprecated
69
+ */
135
70
  async containerReady(options) {
136
71
  if (!this.app.getApplicationContext) {
137
72
  this.defineApplicationProperties();
138
73
  }
139
- await this.applicationContext.ready();
140
- }
141
- async loadExtension() {
142
- // 切面支持
143
- await this.applicationContext.getAspectService().loadAspect();
144
- // 预加载模块支持
145
- await this.loadPreloadModule();
146
- // lifecycle 支持
147
- await this.loadLifeCycles();
148
- }
149
- async containerStop() {
150
- await this.applicationContext.stop();
151
74
  }
152
75
  getApplicationContext() {
153
76
  return this.applicationContext;
154
77
  }
155
78
  getConfiguration(key) {
156
- return this.getApplicationContext()
157
- .getConfigService()
158
- .getConfiguration(key);
79
+ return this.configService.getConfiguration(key);
159
80
  }
160
81
  getCurrentEnvironment() {
161
- return this.getApplicationContext()
162
- .getEnvironmentService()
163
- .getCurrentEnvironment();
82
+ return this.environmentService.getCurrentEnvironment();
164
83
  }
165
84
  getApplication() {
166
85
  return this.app;
@@ -169,44 +88,34 @@ class BaseFramework {
169
88
  this.BaseContextLoggerClass = BaseContextLogger;
170
89
  }
171
90
  createContextLogger(ctx, name) {
172
- const appLogger = this.getLogger(name);
91
+ const appLogger = this.getLogger(name !== null && name !== void 0 ? name : this.ContextLoggerApplyLogger);
173
92
  return new this.BaseContextLoggerClass(ctx, appLogger);
174
93
  }
175
94
  async stop() {
176
95
  await this.beforeStop();
177
- if (this.isMainFramework === true || this.isMainFramework === undefined) {
178
- await this.stopLifeCycles();
179
- await this.containerStop();
180
- }
181
96
  }
182
97
  getAppDir() {
183
- return this.applicationContext.getInformationService().getAppDir();
98
+ return this.informationService.getAppDir();
184
99
  }
185
100
  getBaseDir() {
186
- return this.applicationContext.getInformationService().getBaseDir();
101
+ return this.informationService.getBaseDir();
187
102
  }
188
103
  defineApplicationProperties(applicationProperties = {}, whiteList = []) {
189
104
  const defaultApplicationProperties = {
190
105
  getBaseDir: () => {
191
- return this.getApplicationContext()
192
- .getInformationService()
193
- .getBaseDir();
106
+ return this.getBaseDir();
194
107
  },
195
108
  getAppDir: () => {
196
- return this.getApplicationContext().getInformationService().getAppDir();
109
+ return this.getAppDir();
197
110
  },
198
111
  getEnv: () => {
199
- return this.getApplicationContext()
200
- .getEnvironmentService()
201
- .getCurrentEnvironment();
112
+ return this.getCurrentEnvironment();
202
113
  },
203
114
  getApplicationContext: () => {
204
115
  return this.getApplicationContext();
205
116
  },
206
117
  getConfig: (key) => {
207
- return this.getApplicationContext()
208
- .getConfigService()
209
- .getConfiguration(key);
118
+ return this.getConfiguration(key);
210
119
  },
211
120
  getFrameworkType: () => {
212
121
  return this.getFrameworkType();
@@ -243,20 +152,35 @@ class BaseFramework {
243
152
  return this.createContextLogger(ctx, name);
244
153
  };
245
154
  }
155
+ ctx.setAttr = (key, value) => {
156
+ ctx.requestContext.setAttr(key, value);
157
+ };
158
+ ctx.getAttr = (key) => {
159
+ return ctx.requestContext.getAttr(key);
160
+ };
246
161
  return ctx;
247
162
  },
248
163
  setContextLoggerClass: (BaseContextLogger) => {
249
164
  return this.setContextLoggerClass(BaseContextLogger);
250
165
  },
251
- addConfigObject(obj) {
252
- this.getApplicationContext().getConfigService().addObject(obj);
166
+ addConfigObject: (obj) => {
167
+ this.configService.addObject(obj);
253
168
  },
254
- setAttr(key, value) {
169
+ setAttr: (key, value) => {
255
170
  this.getApplicationContext().setAttr(key, value);
256
171
  },
257
- getAttr(key) {
172
+ getAttr: (key) => {
258
173
  return this.getApplicationContext().getAttr(key);
259
174
  },
175
+ useMiddleware: (middleware) => {
176
+ this.middlewareManager.insertLast(middleware);
177
+ },
178
+ getMiddleware: () => {
179
+ return this.middlewareManager;
180
+ },
181
+ useFilter: (Filter) => {
182
+ this.filterManager.useFilter(Filter);
183
+ },
260
184
  };
261
185
  for (const method of whiteList) {
262
186
  delete defaultApplicationProperties[method];
@@ -264,116 +188,111 @@ class BaseFramework {
264
188
  Object.assign(this.app, defaultApplicationProperties, applicationProperties);
265
189
  }
266
190
  async beforeStop() { }
191
+ /**
192
+ * @deprecated
193
+ */
267
194
  async beforeContainerInitialize(options) { }
195
+ /**
196
+ * @deprecated
197
+ */
268
198
  async afterContainerInitialize(options) { }
199
+ /**
200
+ * @deprecated
201
+ */
269
202
  async afterContainerDirectoryLoad(options) { }
203
+ /**
204
+ * @deprecated
205
+ */
270
206
  async afterContainerReady(options) { }
271
- async loadLifeCycles(isForce = false) {
272
- // agent 不加载生命周期
273
- if (this.app.getProcessType() === interface_1.MidwayProcessTypeEnum.AGENT)
274
- return;
275
- const cycles = decorator_1.listModule(decorator_1.CONFIGURATION_KEY);
276
- const lifecycleInstanceList = [];
277
- for (const cycle of cycles) {
278
- if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
279
- // 函数式写法
280
- cycle.instance = cycle.target;
281
- }
282
- else {
283
- // 普通类写法
284
- const providerId = decorator_1.getProviderId(cycle.target);
285
- cycle.instance =
286
- await this.getApplicationContext().getAsync(providerId);
287
- }
288
- lifecycleInstanceList.push(cycle);
289
- }
290
- // exec onConfigLoad()
291
- for (const cycle of lifecycleInstanceList) {
292
- if (typeof cycle.instance.onConfigLoad === 'function') {
293
- const configData = await cycle.instance.onConfigLoad(this.getApplicationContext());
294
- if (configData) {
295
- this.getApplicationContext().getConfigService().addObject(configData);
207
+ async getMiddleware(lastMiddleware) {
208
+ if (!this.composeMiddleware) {
209
+ this.middlewareManager.insertFirst((async (ctx, next) => {
210
+ let returnResult = undefined;
211
+ try {
212
+ const result = await next();
213
+ returnResult = await this.filterManager.runResultFilter(result, ctx);
296
214
  }
297
- }
298
- }
299
- for (const cycle of lifecycleInstanceList) {
300
- if (typeof cycle.instance.onReady === 'function') {
301
- /**
302
- * 让组件能正确获取到 bind 之后 registerObject 的对象有三个方法
303
- * 1、在 load 之后修改 bind,不太可行
304
- * 2、每次 getAsync 的时候,去掉 namespace,同时还要查找当前全局的变量,性能差
305
- * 3、一般只会在 onReady 的地方执行 registerObject(否则没有全局的意义),这个取巧的办法就是 onReady 传入一个代理,其中绑定当前的 namespace
306
- */
307
- await cycle.instance.onReady(new Proxy(this.getApplicationContext(), {
308
- get: function (target, prop, receiver) {
309
- if (prop === 'getCurrentNamespace' && cycle.namespace) {
310
- return () => {
311
- return cycle.namespace;
312
- };
313
- }
314
- return Reflect.get(target, prop, receiver);
315
- },
316
- }), this.app);
317
- }
215
+ catch (err) {
216
+ returnResult = await this.filterManager.runErrorFilter(err, ctx);
217
+ }
218
+ return returnResult;
219
+ }));
220
+ this.composeMiddleware = await this.middlewareService.compose(this.middlewareManager);
221
+ await this.filterManager.init(this.applicationContext);
318
222
  }
319
- }
320
- async stopLifeCycles() {
321
- const cycles = decorator_1.listModule(decorator_1.CONFIGURATION_KEY);
322
- for (const cycle of cycles) {
323
- let inst;
324
- if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
325
- // 函数式写法
326
- inst = cycle.target;
327
- }
328
- else {
329
- const providerId = decorator_1.getProviderId(cycle.target);
330
- inst = await this.applicationContext.getAsync(providerId);
331
- }
332
- if (inst.onStop && typeof inst.onStop === 'function') {
333
- await inst.onStop(new Proxy(this.getApplicationContext(), {
334
- get: function (target, prop, receiver) {
335
- if (prop === 'getCurrentNamespace' && cycle.namespace) {
336
- return () => {
337
- return cycle.namespace;
338
- };
339
- }
340
- return Reflect.get(target, prop, receiver);
341
- },
342
- }), this.app);
343
- }
223
+ if (lastMiddleware) {
224
+ return await this.middlewareService.compose([
225
+ this.composeMiddleware,
226
+ lastMiddleware,
227
+ ]);
344
228
  }
345
- }
346
- /**
347
- * load preload module for container
348
- * @private
349
- */
350
- async loadPreloadModule() {
351
- // some common decorator implementation
352
- const modules = decorator_1.listPreloadModule();
353
- for (const module of modules) {
354
- // preload init context
355
- await this.applicationContext.getAsync(module);
229
+ else {
230
+ return this.composeMiddleware;
356
231
  }
357
232
  }
358
233
  getLogger(name) {
359
234
  var _a;
360
- return (_a = logger_1.loggers.getLogger(name)) !== null && _a !== void 0 ? _a : this.appLogger;
235
+ return (_a = this.loggerService.getLogger(name)) !== null && _a !== void 0 ? _a : this.appLogger;
361
236
  }
362
237
  getCoreLogger() {
363
238
  return this.logger;
364
239
  }
365
240
  createLogger(name, option = {}) {
366
- return logger_2.createMidwayLogger(this, name, option);
241
+ return this.loggerService.createLogger(name, option);
367
242
  }
368
243
  getProjectName() {
369
- return this.applicationContext.getInformationService().getProjectName();
244
+ return this.informationService.getProjectName();
370
245
  }
371
246
  getFrameworkName() {
372
- return this.getFrameworkType().toString();
247
+ return this.getFrameworkType().name;
373
248
  }
374
249
  getDefaultContextLoggerClass() {
375
250
  return logger_1.MidwayContextLogger;
376
251
  }
252
+ useMiddleware(Middleware) {
253
+ this.middlewareManager.insertLast(Middleware);
254
+ }
255
+ useFilter(Filter) {
256
+ this.filterManager.useFilter(Filter);
257
+ }
258
+ createMiddlewareManager() {
259
+ return new middlewareManager_1.ContextMiddlewareManager();
260
+ }
261
+ createFilterManager() {
262
+ return new filterManager_1.FilterManager();
263
+ }
377
264
  }
265
+ __decorate([
266
+ (0, decorator_1.Inject)(),
267
+ __metadata("design:type", loggerService_1.MidwayLoggerService)
268
+ ], BaseFramework.prototype, "loggerService", void 0);
269
+ __decorate([
270
+ (0, decorator_1.Inject)(),
271
+ __metadata("design:type", environmentService_1.MidwayEnvironmentService)
272
+ ], BaseFramework.prototype, "environmentService", void 0);
273
+ __decorate([
274
+ (0, decorator_1.Inject)(),
275
+ __metadata("design:type", configService_1.MidwayConfigService)
276
+ ], BaseFramework.prototype, "configService", void 0);
277
+ __decorate([
278
+ (0, decorator_1.Inject)(),
279
+ __metadata("design:type", informationService_1.MidwayInformationService)
280
+ ], BaseFramework.prototype, "informationService", void 0);
281
+ __decorate([
282
+ (0, decorator_1.Inject)(),
283
+ __metadata("design:type", middlewareService_1.MidwayMiddlewareService)
284
+ ], BaseFramework.prototype, "middlewareService", void 0);
285
+ __decorate([
286
+ (0, decorator_1.Init)(),
287
+ __metadata("design:type", Function),
288
+ __metadata("design:paramtypes", []),
289
+ __metadata("design:returntype", Promise)
290
+ ], BaseFramework.prototype, "init", null);
291
+ __decorate([
292
+ (0, decorator_1.Destroy)(),
293
+ __metadata("design:type", Function),
294
+ __metadata("design:paramtypes", []),
295
+ __metadata("design:returntype", Promise)
296
+ ], BaseFramework.prototype, "stop", null);
378
297
  exports.BaseFramework = BaseFramework;
379
298
  //# sourceMappingURL=baseFramework.js.map
File without changes
@@ -29,16 +29,13 @@ class DirectoryFileDetector extends AbstractFileDetector {
29
29
  this.directoryFilterArray = [];
30
30
  }
31
31
  run(container) {
32
- const debugLogger = container.getDebugLogger();
33
32
  const loadDirs = [].concat(this.options.loadDir || []);
34
33
  for (const dir of loadDirs) {
35
- const fileResults = glob_1.run(DEFAULT_PATTERN.concat(this.options.pattern || []), {
34
+ const fileResults = (0, glob_1.run)(DEFAULT_PATTERN.concat(this.options.pattern || []), {
36
35
  cwd: dir,
37
36
  ignore: DEFAULT_IGNORE_PATTERN.concat(this.options.ignore || []),
38
37
  });
39
38
  for (const file of fileResults) {
40
- debugLogger(`\nmain:*********** binding "${file}" ***********`);
41
- debugLogger(` namespace => "${this.options.namespace}"`);
42
39
  if (this.directoryFilterArray.length) {
43
40
  for (const resolveFilter of this.directoryFilterArray) {
44
41
  if (typeof resolveFilter.pattern === 'string') {
@@ -50,7 +47,7 @@ class DirectoryFileDetector extends AbstractFileDetector {
50
47
  continue;
51
48
  }
52
49
  }
53
- else if (decorator_1.isRegExp(resolveFilter.pattern)) {
50
+ else if ((0, decorator_1.isRegExp)(resolveFilter.pattern)) {
54
51
  if (resolveFilter.pattern.test(file)) {
55
52
  const exports = resolveFilter.ignoreRequire
56
53
  ? undefined
@@ -61,15 +58,21 @@ class DirectoryFileDetector extends AbstractFileDetector {
61
58
  }
62
59
  const exports = require(file);
63
60
  // add module to set
64
- container.bindClass(exports, this.options.namespace, file);
65
- debugLogger(` binding "${file}" end`);
61
+ container.bindClass(exports, {
62
+ namespace: this.options.namespace,
63
+ srcPath: file,
64
+ createFrom: 'file',
65
+ });
66
66
  }
67
67
  }
68
68
  else {
69
69
  const exports = require(file);
70
70
  // add module to set
71
- container.bindClass(exports, this.options.namespace, file);
72
- debugLogger(` binding "${file}" end`);
71
+ container.bindClass(exports, {
72
+ namespace: this.options.namespace,
73
+ srcPath: file,
74
+ createFrom: 'file',
75
+ });
73
76
  }
74
77
  }
75
78
  }
@@ -79,7 +82,10 @@ exports.DirectoryFileDetector = DirectoryFileDetector;
79
82
  class CustomModuleDetector extends AbstractFileDetector {
80
83
  run(container) {
81
84
  for (const module of this.options.modules) {
82
- container.bindClass(module, this.options.namespace);
85
+ container.bindClass(module, {
86
+ namespace: this.options.namespace,
87
+ createFrom: 'module',
88
+ });
83
89
  }
84
90
  }
85
91
  }
@@ -0,0 +1,19 @@
1
+ import { CommonFilterUnion, IMidwayContainer, IMidwayContext } from '../interface';
2
+ export declare class FilterManager<CTX extends IMidwayContext = IMidwayContext, R = any, N = any> {
3
+ private errFilterList;
4
+ private successFilterList;
5
+ private exceptionMap;
6
+ private defaultErrFilter;
7
+ private matchFnList;
8
+ useFilter(Filters: CommonFilterUnion<CTX, R, N>): void;
9
+ init(applicationContext: IMidwayContainer): Promise<void>;
10
+ runErrorFilter(err: Error, ctx: CTX, res?: R, next?: N): Promise<{
11
+ result: any;
12
+ error: any;
13
+ }>;
14
+ runResultFilter(result: any, ctx: CTX, res?: R, next?: N): Promise<{
15
+ result: any;
16
+ error: any;
17
+ }>;
18
+ }
19
+ //# sourceMappingURL=filterManager.d.ts.map
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FilterManager = void 0;
4
+ const decorator_1 = require("@midwayjs/decorator");
5
+ const util_1 = require("../util");
6
+ class FilterManager {
7
+ constructor() {
8
+ this.errFilterList = [];
9
+ this.successFilterList = [];
10
+ this.exceptionMap = new WeakMap();
11
+ this.defaultErrFilter = undefined;
12
+ this.matchFnList = [];
13
+ }
14
+ useFilter(Filters) {
15
+ if (!Array.isArray(Filters)) {
16
+ Filters = [Filters];
17
+ }
18
+ for (const Filter of Filters) {
19
+ if ((0, decorator_1.getClassMetadata)(decorator_1.CATCH_KEY, Filter)) {
20
+ this.errFilterList.push(Filter);
21
+ }
22
+ if ((0, decorator_1.getClassMetadata)(decorator_1.MATCH_KEY, Filter)) {
23
+ this.successFilterList.push(Filter);
24
+ }
25
+ }
26
+ }
27
+ async init(applicationContext) {
28
+ // for catch exception
29
+ for (const FilterClass of this.errFilterList) {
30
+ const filter = await applicationContext.getAsync(FilterClass);
31
+ const exceptionMetadata = (0, decorator_1.getClassMetadata)(decorator_1.CATCH_KEY, FilterClass);
32
+ if (exceptionMetadata && exceptionMetadata.catchTargets) {
33
+ for (const Exception of exceptionMetadata.catchTargets) {
34
+ this.exceptionMap.set(Exception, filter);
35
+ }
36
+ }
37
+ else {
38
+ // default filter
39
+ this.defaultErrFilter = filter;
40
+ }
41
+ }
42
+ // for success return
43
+ for (const FilterClass of this.successFilterList) {
44
+ const filter = await applicationContext.getAsync(FilterClass);
45
+ const matchMetadata = (0, decorator_1.getClassMetadata)(decorator_1.MATCH_KEY, FilterClass);
46
+ if (matchMetadata && matchMetadata.matchPattern) {
47
+ this.matchFnList.push({
48
+ matchFn: (0, util_1.toPathMatch)(matchMetadata.matchPattern),
49
+ target: filter,
50
+ });
51
+ }
52
+ }
53
+ }
54
+ async runErrorFilter(err, ctx, res, next) {
55
+ let result, error;
56
+ if (this.exceptionMap.has(err.constructor)) {
57
+ const filter = this.exceptionMap.get(err.constructor);
58
+ result = await filter.catch(err, ctx, res, next);
59
+ }
60
+ else if (this.defaultErrFilter) {
61
+ result = await this.defaultErrFilter.catch(err, ctx, res, next);
62
+ }
63
+ else {
64
+ error = err;
65
+ }
66
+ return {
67
+ result,
68
+ error,
69
+ };
70
+ }
71
+ async runResultFilter(result, ctx, res, next) {
72
+ let returnValue = result;
73
+ for (const matchData of this.matchFnList) {
74
+ if (matchData.matchFn(ctx)) {
75
+ returnValue = await matchData.target.match(returnValue, ctx, res, next);
76
+ }
77
+ }
78
+ return {
79
+ result: returnValue,
80
+ error: undefined,
81
+ };
82
+ }
83
+ }
84
+ exports.FilterManager = FilterManager;
85
+ //# sourceMappingURL=filterManager.js.map