@midwayjs/core 3.0.0-beta.6 → 3.0.0

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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/baseFramework.d.ts +2 -1
  3. package/dist/baseFramework.js +17 -11
  4. package/dist/common/applicationManager.d.ts +11 -0
  5. package/dist/common/applicationManager.js +70 -0
  6. package/dist/common/dataListener.d.ts +11 -0
  7. package/dist/common/dataListener.js +43 -0
  8. package/dist/common/fileDetector.js +1 -1
  9. package/dist/common/middlewareManager.d.ts +62 -5
  10. package/dist/common/middlewareManager.js +141 -6
  11. package/dist/common/webGenerator.d.ts +3 -14
  12. package/dist/common/webGenerator.js +23 -31
  13. package/dist/common/webRouterCollector.js +7 -3
  14. package/dist/context/container.js +28 -13
  15. package/dist/context/managedResolverFactory.js +12 -5
  16. package/dist/context/requestContainer.js +2 -0
  17. package/dist/definitions/functionDefinition.d.ts +1 -0
  18. package/dist/definitions/functionDefinition.js +1 -0
  19. package/dist/definitions/objectCreator.js +9 -8
  20. package/dist/definitions/objectDefinition.d.ts +1 -0
  21. package/dist/definitions/objectDefinition.js +1 -0
  22. package/dist/error/base.d.ts +22 -3
  23. package/dist/error/base.js +34 -5
  24. package/dist/error/framework.d.ts +30 -2
  25. package/dist/error/framework.js +56 -13
  26. package/dist/error/http.d.ts +146 -41
  27. package/dist/error/http.js +164 -31
  28. package/dist/error/index.d.ts +1 -1
  29. package/dist/error/index.js +4 -1
  30. package/dist/functional/configuration.d.ts +2 -0
  31. package/dist/functional/configuration.js +10 -0
  32. package/dist/index.d.ts +4 -1
  33. package/dist/index.js +7 -1
  34. package/dist/interface.d.ts +51 -29
  35. package/dist/service/aspectService.js +1 -1
  36. package/dist/service/configService.d.ts +3 -1
  37. package/dist/service/configService.js +23 -17
  38. package/dist/service/decoratorService.js +11 -5
  39. package/dist/service/environmentService.d.ts +1 -1
  40. package/dist/service/frameworkService.d.ts +3 -2
  41. package/dist/service/frameworkService.js +17 -12
  42. package/dist/service/lifeCycleService.js +5 -5
  43. package/dist/service/loggerService.d.ts +1 -1
  44. package/dist/service/middlewareService.d.ts +3 -4
  45. package/dist/service/middlewareService.js +28 -24
  46. package/dist/setup.js +13 -5
  47. package/dist/util/extend.d.ts +2 -0
  48. package/dist/util/extend.js +55 -0
  49. package/dist/util/index.d.ts +9 -0
  50. package/dist/util/index.js +55 -1
  51. package/dist/util/webRouterParam.js +24 -4
  52. package/package.json +10 -11
  53. package/CHANGELOG.md +0 -2174
  54. package/dist/error/code.d.ts +0 -59
  55. package/dist/error/code.js +0 -64
@@ -14,9 +14,19 @@ 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 ? Writable<PowerPartial<ReturnType<T>>> : Writable<PowerPartial<T>>;
18
+ /**
19
+ * Get definition from config
20
+ */
18
21
  export declare type FileConfigOption<T, K = unknown> = K extends keyof ConfigType<T> ? Pick<ConfigType<T>, K> : ConfigType<T>;
19
22
  /**
23
+ * Make object property writeable
24
+ */
25
+ export declare type Writable<T> = {
26
+ -readonly [P in keyof T]: T[P];
27
+ };
28
+ /**
29
+ * Lifecycle Definition
20
30
  * 生命周期定义
21
31
  */
22
32
  export interface ILifeCycle extends Partial<IObjectLifeCycle> {
@@ -29,8 +39,8 @@ export declare type ObjectContext = {
29
39
  originName?: string;
30
40
  };
31
41
  /**
42
+ * Abstract Object Factory
32
43
  * 对象容器抽象
33
- * 默认用Xml容器实现一个
34
44
  */
35
45
  export interface IObjectFactory {
36
46
  registry: IObjectDefinitionRegistry;
@@ -46,32 +56,36 @@ export declare enum ObjectLifeCycleEvent {
46
56
  AFTER_INIT = "afterObjectInit",
47
57
  BEFORE_DESTROY = "beforeObjectDestroy"
48
58
  }
59
+ interface ObjectLifeCycleOptions {
60
+ context: IMidwayContainer;
61
+ definition: IObjectDefinition;
62
+ }
63
+ export interface ObjectBeforeBindOptions extends ObjectLifeCycleOptions {
64
+ replaceCallback: (newDefinition: IObjectDefinition) => void;
65
+ }
66
+ export interface ObjectBeforeCreatedOptions extends ObjectLifeCycleOptions {
67
+ constructorArgs: any[];
68
+ }
69
+ export interface ObjectCreatedOptions<T> extends ObjectLifeCycleOptions {
70
+ replaceCallback: (ins: T) => void;
71
+ }
72
+ export interface ObjectInitOptions extends ObjectLifeCycleOptions {
73
+ }
74
+ export interface ObjectBeforeDestroyOptions extends ObjectLifeCycleOptions {
75
+ }
76
+ /**
77
+ * Object Lifecycle
78
+ * 对象生命周期
79
+ */
49
80
  export interface IObjectLifeCycle {
50
- onBeforeBind(fn: (Clzz: any, options: {
51
- context: IMidwayContainer;
52
- definition: IObjectDefinition;
53
- replaceCallback: (newDefinition: IObjectDefinition) => void;
54
- }) => void): any;
55
- onBeforeObjectCreated(fn: (Clzz: any, options: {
56
- context: IMidwayContainer;
57
- definition: IObjectDefinition;
58
- constructorArgs: any[];
59
- }) => void): any;
60
- onObjectCreated<T>(fn: (ins: T, options: {
61
- context: IMidwayContainer;
62
- definition: IObjectDefinition;
63
- replaceCallback: (ins: T) => void;
64
- }) => void): any;
65
- onObjectInit<T>(fn: (ins: T, options: {
66
- context: IMidwayContainer;
67
- definition: IObjectDefinition;
68
- }) => void): any;
69
- onBeforeObjectDestroy<T>(fn: (ins: T, options: {
70
- context: IMidwayContainer;
71
- definition: IObjectDefinition;
72
- }) => void): any;
81
+ onBeforeBind(fn: (Clzz: any, options: ObjectBeforeBindOptions) => void): any;
82
+ onBeforeObjectCreated(fn: (Clzz: any, options: ObjectBeforeCreatedOptions) => void): any;
83
+ onObjectCreated<T>(fn: (ins: T, options: ObjectCreatedOptions<T>) => void): any;
84
+ onObjectInit<T>(fn: (ins: T, options: ObjectInitOptions) => void): any;
85
+ onBeforeObjectDestroy<T>(fn: (ins: T, options: ObjectBeforeDestroyOptions) => void): any;
73
86
  }
74
87
  /**
88
+ * Object Definition
75
89
  * 对象描述定义
76
90
  */
77
91
  export interface IObjectDefinition {
@@ -112,6 +126,7 @@ export interface IObjectDefinition {
112
126
  metadata: any;
113
127
  }>;
114
128
  createFrom: 'framework' | 'file' | 'module';
129
+ allowDowngrade: boolean;
115
130
  }
116
131
  export interface IObjectCreator {
117
132
  load(): any;
@@ -123,6 +138,7 @@ export interface IObjectCreator {
123
138
  doDestroyAsync(obj: any): Promise<void>;
124
139
  }
125
140
  /**
141
+ * Object Definition Registry
126
142
  * 对象定义存储容器
127
143
  */
128
144
  export interface IObjectDefinitionRegistry {
@@ -279,7 +295,7 @@ export declare type NextFunction = () => Promise<any>;
279
295
  * Common middleware definition
280
296
  */
281
297
  export interface IMiddleware<CTX, R, N = unknown> {
282
- resolve: () => FunctionMiddleware<CTX, R, N>;
298
+ resolve: (app?: IMidwayApplication) => FunctionMiddleware<CTX, R, N> | Promise<FunctionMiddleware<CTX, R, N>>;
283
299
  match?: (ctx?: CTX) => boolean;
284
300
  ignore?: (ctx?: CTX) => boolean;
285
301
  }
@@ -396,13 +412,17 @@ export interface IMidwayBootstrapOptions {
396
412
  appDir?: string;
397
413
  applicationContext?: IMidwayContainer;
398
414
  preloadModules?: any[];
415
+ /**
416
+ * @deprecated please use 'imports'
417
+ */
399
418
  configurationModule?: any | any[];
419
+ imports?: any | any[];
400
420
  moduleDetector?: 'file' | IFileDetector | false;
401
421
  logger?: boolean | ILogger;
402
422
  ignore?: string[];
403
- globalConfig?: {
423
+ globalConfig?: Array<{
404
424
  [environmentName: string]: Record<string, any>;
405
- };
425
+ }> | Record<string, any>;
406
426
  }
407
427
  export interface IConfigurationOptions {
408
428
  logger?: ILogger;
@@ -432,7 +452,8 @@ export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX exten
432
452
  getProjectName(): string;
433
453
  getDefaultContextLoggerClass(): any;
434
454
  useMiddleware(Middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
435
- getMiddleware(lastMiddleware?: CommonMiddleware<CTX, ResOrNext, Next>): Promise<MiddlewareRespond<CTX, ResOrNext, Next>>;
455
+ getMiddleware(): ContextMiddlewareManager<CTX, ResOrNext, Next>;
456
+ applyMiddleware(lastMiddleware?: CommonMiddleware<CTX, ResOrNext, Next>): Promise<MiddlewareRespond<CTX, ResOrNext, Next>>;
436
457
  useFilter(Filter: CommonFilterUnion<CTX, ResOrNext, Next>): any;
437
458
  }
438
459
  export declare const MIDWAY_LOGGER_WRITEABLE_DIR = "MIDWAY_LOGGER_WRITEABLE_DIR";
@@ -449,6 +470,7 @@ export interface MidwayAppInfo {
449
470
  * midway global config definition
450
471
  */
451
472
  export interface MidwayConfig extends FileConfigOption<typeof _default> {
473
+ [customConfigKey: string]: unknown;
452
474
  }
453
475
  export {};
454
476
  //# sourceMappingURL=interface.d.ts.map
@@ -64,7 +64,7 @@ let MidwayAspectService = class MidwayAspectService {
64
64
  */
65
65
  interceptPrototypeMethod(Clz, methodName, aspectObject) {
66
66
  const originMethod = Clz.prototype[methodName];
67
- if ((0, decorator_1.isAsyncFunction)(Clz.prototype[methodName])) {
67
+ if (decorator_1.Types.isAsyncFunction(Clz.prototype[methodName])) {
68
68
  Clz.prototype[methodName] = async function (...args) {
69
69
  var _a, _b, _c;
70
70
  let error, result;
@@ -1,4 +1,4 @@
1
- import { IConfigService } from '../interface';
1
+ import { IConfigService, MidwayAppInfo } from '../interface';
2
2
  import { MidwayEnvironmentService } from './environmentService';
3
3
  import { MidwayInformationService } from './informationService';
4
4
  export declare class MidwayConfigService implements IConfigService {
@@ -7,8 +7,10 @@ export declare class MidwayConfigService implements IConfigService {
7
7
  protected configuration: any;
8
8
  protected isReady: boolean;
9
9
  protected externalObject: Record<string, unknown>[];
10
+ protected appInfo: MidwayAppInfo;
10
11
  protected environmentService: MidwayEnvironmentService;
11
12
  protected informationService: MidwayInformationService;
13
+ protected init(): Promise<void>;
12
14
  add(configFilePaths: any[]): void;
13
15
  addObject(obj: Record<string, unknown>): void;
14
16
  private getEnvSet;
@@ -10,7 +10,6 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.MidwayConfigService = void 0;
13
- const extend = require("extend2");
14
13
  const path_1 = require("path");
15
14
  const util_1 = require("../util");
16
15
  const fs_1 = require("fs");
@@ -18,6 +17,7 @@ const decorator_1 = require("@midwayjs/decorator");
18
17
  const util = require("util");
19
18
  const environmentService_1 = require("./environmentService");
20
19
  const informationService_1 = require("./informationService");
20
+ const extend_1 = require("../util/extend");
21
21
  const debug = util.debuglog('midway:debug');
22
22
  let MidwayConfigService = class MidwayConfigService {
23
23
  constructor() {
@@ -29,6 +29,17 @@ let MidwayConfigService = class MidwayConfigService {
29
29
  this.isReady = false;
30
30
  this.externalObject = [];
31
31
  }
32
+ async init() {
33
+ this.appInfo = {
34
+ pkg: this.informationService.getPkg(),
35
+ name: this.informationService.getProjectName(),
36
+ baseDir: this.informationService.getBaseDir(),
37
+ appDir: this.informationService.getAppDir(),
38
+ HOME: this.informationService.getHome(),
39
+ root: this.informationService.getRoot(),
40
+ env: this.environmentService.getCurrentEnvironment(),
41
+ };
42
+ }
32
43
  add(configFilePaths) {
33
44
  for (const dir of configFilePaths) {
34
45
  if (typeof dir === 'string') {
@@ -63,7 +74,7 @@ let MidwayConfigService = class MidwayConfigService {
63
74
  }
64
75
  addObject(obj) {
65
76
  if (this.isReady) {
66
- extend(true, this.configuration, obj);
77
+ (0, extend_1.extend)(true, this.configuration, obj);
67
78
  }
68
79
  else {
69
80
  this.externalObject.push(obj);
@@ -96,20 +107,9 @@ let MidwayConfigService = class MidwayConfigService {
96
107
  const target = {};
97
108
  for (const filename of [...defaultSet, ...currentEnvSet]) {
98
109
  let config = await this.loadConfig(filename);
99
- if ((0, decorator_1.isFunction)(config)) {
110
+ if (decorator_1.Types.isFunction(config)) {
100
111
  // eslint-disable-next-line prefer-spread
101
- config = config.apply(null, [
102
- {
103
- pkg: this.informationService.getPkg(),
104
- name: this.informationService.getProjectName(),
105
- baseDir: this.informationService.getBaseDir(),
106
- appDir: this.informationService.getAppDir(),
107
- HOME: this.informationService.getHome(),
108
- root: this.informationService.getRoot(),
109
- env: this.environmentService.getCurrentEnvironment(),
110
- },
111
- target,
112
- ]);
112
+ config = config.apply(null, [this.appInfo, target]);
113
113
  }
114
114
  if (!config) {
115
115
  continue;
@@ -120,13 +120,13 @@ let MidwayConfigService = class MidwayConfigService {
120
120
  else {
121
121
  debug('[config]: Loaded config %j', config);
122
122
  }
123
- extend(true, target, config);
123
+ (0, extend_1.extend)(true, target, config);
124
124
  }
125
125
  if (this.externalObject.length) {
126
126
  for (const externalObject of this.externalObject) {
127
127
  if (externalObject) {
128
128
  debug('[config]: Loaded external object %j', externalObject);
129
- extend(true, target, externalObject);
129
+ (0, extend_1.extend)(true, target, externalObject);
130
130
  }
131
131
  }
132
132
  }
@@ -160,6 +160,12 @@ __decorate([
160
160
  (0, decorator_1.Inject)(),
161
161
  __metadata("design:type", informationService_1.MidwayInformationService)
162
162
  ], MidwayConfigService.prototype, "informationService", void 0);
163
+ __decorate([
164
+ (0, decorator_1.Init)(),
165
+ __metadata("design:type", Function),
166
+ __metadata("design:paramtypes", []),
167
+ __metadata("design:returntype", Promise)
168
+ ], MidwayConfigService.prototype, "init", null);
163
169
  MidwayConfigService = __decorate([
164
170
  (0, decorator_1.Provide)(),
165
171
  (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton)
@@ -30,7 +30,10 @@ let MidwayDecoratorService = class MidwayDecoratorService {
30
30
  if (methodDecoratorMetadataList) {
31
31
  // loop it, save this order for decorator run
32
32
  for (const meta of methodDecoratorMetadataList) {
33
- const { propertyName, key, metadata } = meta;
33
+ const { propertyName, key, metadata, impl } = meta;
34
+ if (!impl) {
35
+ continue;
36
+ }
34
37
  // add aspect implementation first
35
38
  this.aspectService.interceptPrototypeMethod(Clzz, propertyName, () => {
36
39
  const methodDecoratorHandler = this.methodDecoratorMap.get(key);
@@ -57,7 +60,10 @@ let MidwayDecoratorService = class MidwayDecoratorService {
57
60
  // joinPoint.args
58
61
  const newArgs = [...joinPoint.args];
59
62
  for (const meta of parameterDecoratorMetadata[methodName]) {
60
- const { propertyName, key, metadata, parameterIndex } = meta;
63
+ const { propertyName, key, metadata, parameterIndex, impl } = meta;
64
+ if (!impl) {
65
+ continue;
66
+ }
61
67
  const parameterDecoratorHandler = this.parameterDecoratorMap.get(key);
62
68
  if (!parameterDecoratorHandler) {
63
69
  throw new error_1.MidwayCommonError(`Parameter Decorator "${key}" handler not found, please register first.`);
@@ -95,15 +101,15 @@ let MidwayDecoratorService = class MidwayDecoratorService {
95
101
  });
96
102
  }
97
103
  registerPropertyHandler(decoratorKey, fn) {
98
- debug(`[core:decorator]: Register property decorator key="${decoratorKey}"`);
104
+ debug(`[core]: Register property decorator key="${decoratorKey}"`);
99
105
  this.propertyHandlerMap.set(decoratorKey, fn);
100
106
  }
101
107
  registerMethodHandler(decoratorKey, fn) {
102
- debug(`[core:decorator]: Register method decorator key="${decoratorKey}"`);
108
+ debug(`[core]: Register method decorator key="${decoratorKey}"`);
103
109
  this.methodDecoratorMap.set(decoratorKey, fn);
104
110
  }
105
111
  registerParameterHandler(decoratorKey, fn) {
106
- debug(`[core:decorator]: Register parameter decorator key="${decoratorKey}"`);
112
+ debug(`[core]: Register parameter decorator key="${decoratorKey}"`);
107
113
  this.parameterDecoratorMap.set(decoratorKey, fn);
108
114
  }
109
115
  /**
@@ -1,6 +1,6 @@
1
1
  import { IEnvironmentService } from '../interface';
2
2
  export declare class MidwayEnvironmentService implements IEnvironmentService {
3
- environment: string;
3
+ protected environment: string;
4
4
  getCurrentEnvironment(): string;
5
5
  setCurrentEnvironment(environment: string): void;
6
6
  isDevelopmentEnvironment(): boolean;
@@ -4,6 +4,7 @@ import { MidwayConfigService } from './configService';
4
4
  import { MidwayLoggerService } from './loggerService';
5
5
  import { MidwayDecoratorService } from './decoratorService';
6
6
  import { MidwayAspectService } from './aspectService';
7
+ import { MidwayApplicationManager } from '../common/applicationManager';
7
8
  export declare class MidwayFrameworkService {
8
9
  readonly applicationContext: IMidwayContainer;
9
10
  readonly globalOptions: any;
@@ -11,14 +12,14 @@ export declare class MidwayFrameworkService {
11
12
  loggerService: MidwayLoggerService;
12
13
  aspectService: MidwayAspectService;
13
14
  decoratorService: MidwayDecoratorService;
15
+ applicationManager: MidwayApplicationManager;
14
16
  constructor(applicationContext: IMidwayContainer, globalOptions: any);
15
17
  private mainFramework;
16
- private globalFrameworkMap;
17
18
  private globalFrameworkList;
18
19
  protected init(): Promise<void>;
19
20
  getMainApp(): any;
20
21
  getMainFramework(): IMidwayFramework<any, any, any, unknown, unknown>;
21
- getFramework(type: MidwayFrameworkType): IMidwayFramework<any, any, any, unknown, unknown>;
22
+ getFramework(namespaceOrFrameworkType: string | MidwayFrameworkType): IMidwayFramework<any, any, any, unknown, unknown>;
22
23
  runFramework(): Promise<void>;
23
24
  stopFramework(): Promise<void>;
24
25
  }
@@ -18,6 +18,7 @@ const baseFramework_1 = require("../baseFramework");
18
18
  const pipelineService_1 = require("./pipelineService");
19
19
  const decoratorService_1 = require("./decoratorService");
20
20
  const aspectService_1 = require("./aspectService");
21
+ const applicationManager_1 = require("../common/applicationManager");
21
22
  const util = require("util");
22
23
  const error_1 = require("../error");
23
24
  const debug = util.debuglog('midway:debug');
@@ -25,10 +26,10 @@ let MidwayFrameworkService = class MidwayFrameworkService {
25
26
  constructor(applicationContext, globalOptions) {
26
27
  this.applicationContext = applicationContext;
27
28
  this.globalOptions = globalOptions;
28
- this.globalFrameworkMap = new WeakMap();
29
29
  this.globalFrameworkList = [];
30
30
  }
31
31
  async init() {
32
+ var _a;
32
33
  // register base config hook
33
34
  this.decoratorService.registerPropertyHandler(decorator_1.CONFIG_KEY, (propertyName, meta) => {
34
35
  var _a;
@@ -51,7 +52,7 @@ let MidwayFrameworkService = class MidwayFrameworkService {
51
52
  let frameworks = (0, decorator_1.listModule)(decorator_1.FRAMEWORK_KEY);
52
53
  // filter proto
53
54
  frameworks = filterProtoFramework(frameworks);
54
- debug(`[core:framework]: Found Framework length = ${frameworks.length}`);
55
+ debug(`[core]: Found Framework length = ${frameworks.length}`);
55
56
  if (frameworks.length) {
56
57
  for (const frameworkClz of frameworks) {
57
58
  const frameworkInstance = await this.applicationContext.getAsync(frameworkClz, [this.applicationContext]);
@@ -62,24 +63,24 @@ let MidwayFrameworkService = class MidwayFrameworkService {
62
63
  applicationContext: this.applicationContext,
63
64
  ...this.globalOptions,
64
65
  });
65
- debug(`[core:framework]: Found Framework "${frameworkInstance.getFrameworkName()}" and initialize.`);
66
+ debug(`[core]: Found Framework "${frameworkInstance.getFrameworkName()}" and initialize.`);
66
67
  }
67
68
  else {
68
- debug(`[core:framework]: Found Framework "${frameworkInstance.getFrameworkName()}" and delay initialize.`);
69
+ debug(`[core]: Found Framework "${frameworkInstance.getFrameworkName()}" and delay initialize.`);
69
70
  }
70
71
  // app init
71
- this.globalFrameworkMap.set(frameworkInstance.getFrameworkType(), frameworkInstance);
72
+ const definition = this.applicationContext.registry.getDefinition((0, decorator_1.getProviderUUId)(frameworkClz));
73
+ this.applicationManager.addFramework((_a = definition === null || definition === void 0 ? void 0 : definition.namespace) !== null && _a !== void 0 ? _a : frameworkInstance.getFrameworkName(), frameworkInstance);
72
74
  this.globalFrameworkList.push(frameworkInstance);
73
75
  }
74
76
  // register @App decorator handler
75
77
  this.decoratorService.registerPropertyHandler(decorator_1.APPLICATION_KEY, (propertyName, mete) => {
76
78
  if (mete.type) {
77
- if (this.globalFrameworkMap.has(mete.type)) {
78
- return this.globalFrameworkMap.get(mete.type).getApplication();
79
- }
80
- else {
79
+ const framework = this.applicationManager.getApplication(mete.type);
80
+ if (!framework) {
81
81
  throw new error_1.MidwayCommonError(`Framework ${mete.type} not Found`);
82
82
  }
83
+ return framework;
83
84
  }
84
85
  else {
85
86
  return this.getMainApp();
@@ -107,8 +108,8 @@ let MidwayFrameworkService = class MidwayFrameworkService {
107
108
  getMainFramework() {
108
109
  return this.mainFramework;
109
110
  }
110
- getFramework(type) {
111
- return this.globalFrameworkMap.get(type);
111
+ getFramework(namespaceOrFrameworkType) {
112
+ return this.applicationManager.getFramework(namespaceOrFrameworkType);
112
113
  }
113
114
  async runFramework() {
114
115
  for (const frameworkInstance of this.globalFrameworkList) {
@@ -116,7 +117,7 @@ let MidwayFrameworkService = class MidwayFrameworkService {
116
117
  if (frameworkInstance.isEnable()) {
117
118
  // app init
118
119
  await frameworkInstance.run();
119
- debug(`[core:framework]: Found Framework "${frameworkInstance.getFrameworkName()}" and run.`);
120
+ debug(`[core]: Found Framework "${frameworkInstance.getFrameworkName()}" and run.`);
120
121
  }
121
122
  }
122
123
  }
@@ -142,6 +143,10 @@ __decorate([
142
143
  (0, decorator_1.Inject)(),
143
144
  __metadata("design:type", decoratorService_1.MidwayDecoratorService)
144
145
  ], MidwayFrameworkService.prototype, "decoratorService", void 0);
146
+ __decorate([
147
+ (0, decorator_1.Inject)(),
148
+ __metadata("design:type", applicationManager_1.MidwayApplicationManager)
149
+ ], MidwayFrameworkService.prototype, "applicationManager", void 0);
145
150
  __decorate([
146
151
  (0, decorator_1.Init)(),
147
152
  __metadata("design:type", Function),
@@ -23,7 +23,7 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
23
23
  async init() {
24
24
  // run lifecycle
25
25
  const cycles = (0, decorator_1.listModule)(decorator_1.CONFIGURATION_KEY);
26
- debug(`[core:lifecycle]: Found Configuration length = ${cycles.length}`);
26
+ debug(`[core]: Found Configuration length = ${cycles.length}`);
27
27
  const lifecycleInstanceList = [];
28
28
  for (const cycle of cycles) {
29
29
  if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
@@ -32,7 +32,7 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
32
32
  }
33
33
  else {
34
34
  // 普通类写法
35
- debug(`[core:lifecycle]: run ${cycle.target.name} init`);
35
+ debug(`[core]: run ${cycle.target.name} init`);
36
36
  cycle.instance = await this.applicationContext.getAsync(cycle.target);
37
37
  }
38
38
  cycle.instance && lifecycleInstanceList.push(cycle);
@@ -80,7 +80,7 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
80
80
  if (Array.isArray(lifecycleInstanceOrList)) {
81
81
  for (const cycle of lifecycleInstanceOrList) {
82
82
  if (typeof cycle.instance[lifecycle] === 'function') {
83
- debug(`[core:lifecycle]: run ${cycle.instance.constructor.name} ${lifecycle}`);
83
+ debug(`[core]: run ${cycle.instance.constructor.name} ${lifecycle}`);
84
84
  const result = await cycle.instance[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
85
85
  if (resultHandler) {
86
86
  resultHandler(result);
@@ -90,7 +90,7 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
90
90
  }
91
91
  else {
92
92
  if (typeof lifecycleInstanceOrList[lifecycle] === 'function') {
93
- debug(`[core:lifecycle]: run ${lifecycleInstanceOrList.constructor.name} ${lifecycle}`);
93
+ debug(`[core]: run ${lifecycleInstanceOrList.constructor.name} ${lifecycle}`);
94
94
  const result = await lifecycleInstanceOrList[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
95
95
  if (resultHandler) {
96
96
  resultHandler(result);
@@ -101,7 +101,7 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
101
101
  async runObjectLifeCycle(lifecycleInstanceList, lifecycle) {
102
102
  for (const cycle of lifecycleInstanceList) {
103
103
  if (typeof cycle.instance[lifecycle] === 'function') {
104
- debug(`[core:lifecycle]: run ${cycle.instance.constructor.name} ${lifecycle}`);
104
+ debug(`[core]: run ${cycle.instance.constructor.name} ${lifecycle}`);
105
105
  return this.applicationContext[lifecycle](cycle.instance[lifecycle].bind(cycle.instance));
106
106
  }
107
107
  }
@@ -7,7 +7,7 @@ export declare class MidwayLoggerService extends ServiceFactory<ILogger> {
7
7
  configService: MidwayConfigService;
8
8
  constructor(applicationContext: IMidwayContainer);
9
9
  protected init(): Promise<void>;
10
- transformEggConfig(): {
10
+ protected transformEggConfig(): {
11
11
  midwayLogger: {
12
12
  default: {};
13
13
  clients: {};
@@ -1,11 +1,10 @@
1
- import { CommonMiddleware, IMidwayContainer } from '../interface';
1
+ import { CommonMiddleware, IMidwayContainer, IMidwayApplication } from '../interface';
2
2
  export declare class MidwayMiddlewareService<T, R, N = unknown> {
3
3
  readonly applicationContext: IMidwayContainer;
4
4
  constructor(applicationContext: IMidwayContainer);
5
- compose(middleware: Array<CommonMiddleware<T, R, N> | string>, name?: string): Promise<{
6
- (context: any, next?: any): Promise<any>;
5
+ compose(middleware: Array<CommonMiddleware<T, R, N> | string>, app: IMidwayApplication, name?: string): Promise<{
6
+ (context: T, next?: any): Promise<any>;
7
7
  _name: string;
8
8
  }>;
9
9
  }
10
- export declare function pathMatching(options: any): (ctx?: any) => any;
11
10
  //# sourceMappingURL=middlewareService.d.ts.map
@@ -9,7 +9,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.pathMatching = exports.MidwayMiddlewareService = void 0;
12
+ exports.MidwayMiddlewareService = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const error_1 = require("../error");
15
15
  const util_1 = require("../util");
@@ -17,29 +17,31 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
17
17
  constructor(applicationContext) {
18
18
  this.applicationContext = applicationContext;
19
19
  }
20
- async compose(middleware, name) {
20
+ async compose(middleware, app, name) {
21
21
  if (!Array.isArray(middleware)) {
22
22
  throw new error_1.MidwayParameterError('Middleware stack must be an array');
23
23
  }
24
24
  const newMiddlewareArr = [];
25
25
  for (let fn of middleware) {
26
- if ((0, decorator_1.isClass)(fn) || typeof fn === 'string') {
26
+ if (decorator_1.Types.isClass(fn) || typeof fn === 'string') {
27
27
  if (typeof fn === 'string' &&
28
28
  !this.applicationContext.hasDefinition(fn)) {
29
29
  throw new error_1.MidwayCommonError('Middleware definition not found in midway container');
30
30
  }
31
31
  const classMiddleware = await this.applicationContext.getAsync(fn);
32
32
  if (classMiddleware) {
33
- fn = classMiddleware.resolve();
33
+ fn = await classMiddleware.resolve(app);
34
34
  if (!classMiddleware.match && !classMiddleware.ignore) {
35
- fn._name = classMiddleware.constructor.name;
35
+ if (!fn.name) {
36
+ fn._name = classMiddleware.constructor.name;
37
+ }
36
38
  // just got fn
37
39
  newMiddlewareArr.push(fn);
38
40
  }
39
41
  else {
40
42
  // wrap ignore and match
41
43
  const mw = fn;
42
- const match = pathMatching({
44
+ const match = (0, util_1.pathMatching)({
43
45
  match: classMiddleware.match,
44
46
  ignore: classMiddleware.ignore,
45
47
  });
@@ -67,6 +69,7 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
67
69
  * @api public
68
70
  */
69
71
  const composeFn = (context, next) => {
72
+ const supportBody = (0, util_1.isIncludeProperty)(context, 'body');
70
73
  // last called middleware #
71
74
  let index = -1;
72
75
  return dispatch(0);
@@ -80,9 +83,25 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
80
83
  if (!fn)
81
84
  return Promise.resolve();
82
85
  try {
83
- return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
84
- index,
85
- }));
86
+ if (supportBody) {
87
+ return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
88
+ index,
89
+ })).then(result => {
90
+ // need to set body
91
+ if (context['body'] && !result) {
92
+ result = context['body'];
93
+ }
94
+ else if (result && context['body'] !== result) {
95
+ context['body'] = result;
96
+ }
97
+ return result;
98
+ });
99
+ }
100
+ else {
101
+ return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
102
+ index,
103
+ }));
104
+ }
86
105
  }
87
106
  catch (err) {
88
107
  return Promise.reject(err);
@@ -101,19 +120,4 @@ MidwayMiddlewareService = __decorate([
101
120
  __metadata("design:paramtypes", [Object])
102
121
  ], MidwayMiddlewareService);
103
122
  exports.MidwayMiddlewareService = MidwayMiddlewareService;
104
- function pathMatching(options) {
105
- options = options || {};
106
- if (options.match && options.ignore)
107
- throw new error_1.MidwayCommonError('options.match and options.ignore can not both present');
108
- if (!options.match && !options.ignore)
109
- return () => true;
110
- const matchFn = options.match
111
- ? (0, util_1.toPathMatch)(options.match)
112
- : (0, util_1.toPathMatch)(options.ignore);
113
- return function pathMatch(ctx) {
114
- const matched = matchFn(ctx);
115
- return options.match ? matched : !matched;
116
- };
117
- }
118
- exports.pathMatching = pathMatching;
119
123
  //# sourceMappingURL=middlewareService.js.map
package/dist/setup.js CHANGED
@@ -22,7 +22,7 @@ async function initializeGlobalApplicationContext(globalOptions) {
22
22
  // register baseDir and appDir
23
23
  applicationContext.registerObject('baseDir', baseDir);
24
24
  applicationContext.registerObject('appDir', appDir);
25
- if (globalOptions.moduleDirector !== false) {
25
+ if (globalOptions.moduleDetector !== false) {
26
26
  if (globalOptions.moduleDetector === undefined ||
27
27
  globalOptions.moduleDetector === 'file') {
28
28
  applicationContext.setFileDetector(new _1.DirectoryFileDetector({
@@ -44,6 +44,7 @@ async function initializeGlobalApplicationContext(globalOptions) {
44
44
  applicationContext.bindClass(_1.MidwayFrameworkService);
45
45
  applicationContext.bindClass(_1.MidwayMiddlewareService);
46
46
  applicationContext.bindClass(_1.MidwayLifeCycleService);
47
+ applicationContext.bindClass(_1.MidwayApplicationManager);
47
48
  // bind preload module
48
49
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
49
50
  for (const preloadModule of globalOptions.preloadModules) {
@@ -63,19 +64,26 @@ async function initializeGlobalApplicationContext(globalOptions) {
63
64
  await applicationContext.getAsync(_1.MidwayDecoratorService, [
64
65
  applicationContext,
65
66
  ]);
66
- if (!globalOptions.configurationModule) {
67
- globalOptions.configurationModule = [
67
+ if (!globalOptions.imports) {
68
+ globalOptions.imports = [
68
69
  (0, _1.safeRequire)((0, path_1.join)(globalOptions.baseDir, 'configuration')),
69
70
  ];
70
71
  }
71
- for (const configurationModule of [].concat(globalOptions.configurationModule)) {
72
+ for (const configurationModule of []
73
+ .concat(globalOptions.imports)
74
+ .concat(globalOptions.configurationModule)) {
72
75
  // load configuration and component
73
76
  applicationContext.load(configurationModule);
74
77
  }
75
78
  // bind user code module
76
79
  await applicationContext.ready();
77
80
  if (globalOptions.globalConfig) {
78
- configService.add([globalOptions.globalConfig]);
81
+ if (Array.isArray(globalOptions.globalConfig)) {
82
+ configService.add(globalOptions.globalConfig);
83
+ }
84
+ else {
85
+ configService.addObject(globalOptions.globalConfig);
86
+ }
79
87
  }
80
88
  // merge config
81
89
  await configService.load();