@midwayjs/core 3.19.0-beta.1 → 3.19.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -44,6 +44,9 @@ export declare abstract class DataSourceManager<T, ConnectionOpts extends Record
44
44
  protected abstract createDataSource(config: any, dataSourceName: string): Promise<T | void> | (T | void);
45
45
  protected abstract checkConnected(dataSource: T): Promise<boolean>;
46
46
  protected abstract destroyDataSource(dataSource: T): Promise<void>;
47
+ /**
48
+ * Call destroyDataSource() on all data sources
49
+ */
47
50
  stop(): Promise<void>;
48
51
  getDefaultDataSourceName(): string;
49
52
  getDataSourcePriority(name: string): string;
@@ -134,6 +134,9 @@ class DataSourceManager {
134
134
  getDataSourceNameByModel(modelOrRepository) {
135
135
  return this.modelMapping.get(modelOrRepository);
136
136
  }
137
+ /**
138
+ * Call destroyDataSource() on all data sources
139
+ */
137
140
  async stop() {
138
141
  const arr = Array.from(this.dataSource.values());
139
142
  await Promise.all(arr.map(dbh => {
@@ -16,9 +16,9 @@ export declare class MidwayPerformanceManager {
16
16
  markEnd(key: string): void;
17
17
  observeMeasure(callback: (list: PerformanceObserverEntryList) => void): PerformanceObserver;
18
18
  disconnect(): void;
19
- getGroup(): string;
20
19
  clean(): void;
21
20
  static cleanAll(): void;
21
+ static getInitialPerformanceEntries(): any[];
22
22
  }
23
23
  export declare class MidwayInitializerPerformanceManager {
24
24
  static MEASURE_KEYS: {
@@ -29,15 +29,17 @@ export declare class MidwayInitializerPerformanceManager {
29
29
  CONFIG_LOAD: string;
30
30
  LOGGER_PREPARE: string;
31
31
  FRAMEWORK_PREPARE: string;
32
- CUSTOM_FRAMEWORK_PREPARE: string;
32
+ FRAMEWORK_INITIALIZE: string;
33
+ FRAMEWORK_RUN: string;
33
34
  LIFECYCLE_PREPARE: string;
34
- CUSTOM_LIFECYCLE_PREPARE: string;
35
35
  PRELOAD_MODULE_PREPARE: string;
36
36
  };
37
37
  static markStart(key: string): void;
38
38
  static markEnd(key: string): void;
39
39
  static frameworkInitializeStart(frameworkName: string): void;
40
40
  static frameworkInitializeEnd(frameworkName: string): void;
41
+ static frameworkRunStart(frameworkName: string): void;
42
+ static frameworkRunEnd(frameworkName: string): void;
41
43
  static lifecycleStart(namespace: string, lifecycleName: string): void;
42
44
  static lifecycleEnd(namespace: string, lifecycleName: string): void;
43
45
  }
@@ -55,9 +55,6 @@ class MidwayPerformanceManager {
55
55
  this.observer = null;
56
56
  }
57
57
  }
58
- getGroup() {
59
- return this.group;
60
- }
61
58
  clean() {
62
59
  this.marks.forEach(mark => {
63
60
  try {
@@ -83,6 +80,15 @@ class MidwayPerformanceManager {
83
80
  this.instances.forEach(instance => instance.clean());
84
81
  this.instances.clear();
85
82
  }
83
+ static getInitialPerformanceEntries() {
84
+ const entries = [];
85
+ perf_hooks_1.performance === null || perf_hooks_1.performance === void 0 ? void 0 : perf_hooks_1.performance.getEntries().forEach(entry => {
86
+ if (entry.name.startsWith(this.DEFAULT_GROUP.INITIALIZE)) {
87
+ entries.push(entry.toJSON());
88
+ }
89
+ });
90
+ return entries;
91
+ }
86
92
  }
87
93
  exports.MidwayPerformanceManager = MidwayPerformanceManager;
88
94
  MidwayPerformanceManager.instances = new Map();
@@ -99,16 +105,22 @@ class MidwayInitializerPerformanceManager {
99
105
  manager.markEnd(key);
100
106
  }
101
107
  static frameworkInitializeStart(frameworkName) {
102
- this.markStart(`${this.MEASURE_KEYS.CUSTOM_FRAMEWORK_PREPARE}:${frameworkName}`);
108
+ this.markStart(`${this.MEASURE_KEYS.FRAMEWORK_INITIALIZE}:${frameworkName}`);
103
109
  }
104
110
  static frameworkInitializeEnd(frameworkName) {
105
- this.markEnd(`${this.MEASURE_KEYS.CUSTOM_FRAMEWORK_PREPARE}:${frameworkName}`);
111
+ this.markEnd(`${this.MEASURE_KEYS.FRAMEWORK_INITIALIZE}:${frameworkName}`);
112
+ }
113
+ static frameworkRunStart(frameworkName) {
114
+ this.markStart(`${this.MEASURE_KEYS.FRAMEWORK_RUN}:${frameworkName}`);
115
+ }
116
+ static frameworkRunEnd(frameworkName) {
117
+ this.markEnd(`${this.MEASURE_KEYS.FRAMEWORK_RUN}:${frameworkName}`);
106
118
  }
107
119
  static lifecycleStart(namespace, lifecycleName) {
108
- this.markStart(`${this.MEASURE_KEYS.CUSTOM_LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
120
+ this.markStart(`${this.MEASURE_KEYS.LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
109
121
  }
110
122
  static lifecycleEnd(namespace, lifecycleName) {
111
- this.markEnd(`${this.MEASURE_KEYS.CUSTOM_LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
123
+ this.markEnd(`${this.MEASURE_KEYS.LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
112
124
  }
113
125
  }
114
126
  exports.MidwayInitializerPerformanceManager = MidwayInitializerPerformanceManager;
@@ -120,9 +132,9 @@ MidwayInitializerPerformanceManager.MEASURE_KEYS = {
120
132
  CONFIG_LOAD: 'ConfigLoad',
121
133
  LOGGER_PREPARE: 'LoggerPrepare',
122
134
  FRAMEWORK_PREPARE: 'FrameworkPrepare',
123
- CUSTOM_FRAMEWORK_PREPARE: 'CustomFrameworkPrepare',
135
+ FRAMEWORK_INITIALIZE: 'FrameworkInitialize',
136
+ FRAMEWORK_RUN: 'FrameworkRun',
124
137
  LIFECYCLE_PREPARE: 'LifecyclePrepare',
125
- CUSTOM_LIFECYCLE_PREPARE: 'CustomLifecyclePrepare',
126
138
  PRELOAD_MODULE_PREPARE: 'PreloadModulePrepare',
127
139
  };
128
140
  //# sourceMappingURL=performanceManager.js.map
@@ -46,6 +46,8 @@ class TypedResourceManager {
46
46
  for (const [resourceName, resource] of this.resourceMap.entries()) {
47
47
  await this.typedResourceInitializerOptions.resourceDestroy(resource, this.typedResourceInitializerOptions.initializeValue[resourceName]);
48
48
  }
49
+ this.resourceMap.clear();
50
+ this.resourceBindingMap.clear();
49
51
  }
50
52
  getResource(resourceName) {
51
53
  return this.resourceMap.get(resourceName);
package/dist/index.d.ts CHANGED
@@ -47,5 +47,6 @@ export { PathFileUtil } from './util/pathFileUtil';
47
47
  export { FileUtils } from './util/fs';
48
48
  export { FORMAT } from './util/format';
49
49
  export { ServerResponse, HttpServerResponse } from './response/index';
50
+ export { TypedResourceManager } from './common/typedResourceManager';
50
51
  export { MidwayPerformanceManager } from './common/performanceManager';
51
52
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.MidwayPerformanceManager = exports.HttpServerResponse = exports.ServerResponse = exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.retryWith = exports.retryWithAsync = exports.extend = exports.Utils = exports.sleep = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = exports.ASYNC_ROOT_CONTEXT = exports.MidwayPriorityManager = exports.DEFAULT_PRIORITY = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayHealthService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
17
+ exports.MidwayPerformanceManager = exports.TypedResourceManager = exports.HttpServerResponse = exports.ServerResponse = exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.retryWith = exports.retryWithAsync = exports.extend = exports.Utils = exports.sleep = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = exports.ASYNC_ROOT_CONTEXT = exports.MidwayPriorityManager = exports.DEFAULT_PRIORITY = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayHealthService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
18
18
  __exportStar(require("./interface"), exports);
19
19
  __exportStar(require("./context/container"), exports);
20
20
  var requestContainer_1 = require("./context/requestContainer");
@@ -112,6 +112,8 @@ Object.defineProperty(exports, "FORMAT", { enumerable: true, get: function () {
112
112
  var index_1 = require("./response/index");
113
113
  Object.defineProperty(exports, "ServerResponse", { enumerable: true, get: function () { return index_1.ServerResponse; } });
114
114
  Object.defineProperty(exports, "HttpServerResponse", { enumerable: true, get: function () { return index_1.HttpServerResponse; } });
115
+ var typedResourceManager_1 = require("./common/typedResourceManager");
116
+ Object.defineProperty(exports, "TypedResourceManager", { enumerable: true, get: function () { return typedResourceManager_1.TypedResourceManager; } });
115
117
  var performanceManager_1 = require("./common/performanceManager");
116
118
  Object.defineProperty(exports, "MidwayPerformanceManager", { enumerable: true, get: function () { return performanceManager_1.MidwayPerformanceManager; } });
117
119
  //# sourceMappingURL=index.js.map
@@ -1011,5 +1011,6 @@ export interface ServerSendEventStreamOptions<CTX extends IMidwayContext> {
1011
1011
  closeEvent?: string;
1012
1012
  tpl?: (data: ServerSendEventMessage, ctx: CTX) => ServerSendEventMessage;
1013
1013
  }
1014
+ export type ClassType<T = any> = new (...args: any[]) => T;
1014
1015
  export {};
1015
1016
  //# sourceMappingURL=interface.d.ts.map
@@ -34,9 +34,7 @@ class ServerSendEventStream extends stream_1.Transform {
34
34
  this.ctx.req.socket.setTimeout(0);
35
35
  this.ctx.req.socket.setNoDelay(true);
36
36
  this.ctx.req.socket.setKeepAlive(true);
37
- res.push({
38
- data: ':ok',
39
- });
37
+ res.push(': ok');
40
38
  }
41
39
  const senderObject = chunk;
42
40
  if (senderObject.event)
@@ -7,5 +7,6 @@ export declare class MidwayEnvironmentService implements IEnvironmentService {
7
7
  isDevelopmentEnvironment(): boolean;
8
8
  setModuleLoadType(moduleLoadType: ModuleLoadType): void;
9
9
  getModuleLoadType(): ModuleLoadType;
10
+ isPkgEnvironment(): boolean;
10
11
  }
11
12
  //# sourceMappingURL=environmentService.d.ts.map
@@ -32,6 +32,9 @@ let MidwayEnvironmentService = class MidwayEnvironmentService {
32
32
  getModuleLoadType() {
33
33
  return this.moduleLoadType;
34
34
  }
35
+ isPkgEnvironment() {
36
+ return typeof process['pkg'] !== 'undefined';
37
+ }
35
38
  };
36
39
  MidwayEnvironmentService = __decorate([
37
40
  (0, decorator_1.Provide)(),
@@ -159,9 +159,11 @@ let MidwayFrameworkService = class MidwayFrameworkService {
159
159
  for (const frameworkInstance of this.globalFrameworkList) {
160
160
  // if enable, just init framework
161
161
  if (frameworkInstance.isEnable()) {
162
+ performanceManager_1.MidwayInitializerPerformanceManager.frameworkRunStart(frameworkInstance.getFrameworkName());
162
163
  // app init
163
164
  await frameworkInstance.run();
164
165
  debug(`[core]: Found Framework "${frameworkInstance.getFrameworkName()}" and run.`);
166
+ performanceManager_1.MidwayInitializerPerformanceManager.frameworkRunEnd(frameworkInstance.getFrameworkName());
165
167
  }
166
168
  }
167
169
  }
@@ -101,20 +101,25 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
101
101
  for (const cycle of lifecycleInstanceOrList) {
102
102
  if (typeof cycle.instance[lifecycle] === 'function') {
103
103
  debug(`[core]: Lifecycle run ${cycle.instance.constructor.name} ${lifecycle}`);
104
+ performanceManager_1.MidwayInitializerPerformanceManager.lifecycleStart(cycle.namespace, lifecycle);
104
105
  const result = await cycle.instance[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
105
106
  if (resultHandler) {
106
107
  resultHandler(result);
107
108
  }
109
+ performanceManager_1.MidwayInitializerPerformanceManager.lifecycleEnd(cycle.namespace, lifecycle);
108
110
  }
109
111
  }
110
112
  }
111
113
  else {
112
114
  if (typeof lifecycleInstanceOrList[lifecycle] === 'function') {
113
- debug(`[core]: Lifecycle run ${lifecycleInstanceOrList.constructor.name} ${lifecycle}`);
115
+ const name = lifecycleInstanceOrList.constructor.name;
116
+ debug(`[core]: Lifecycle run ${name} ${lifecycle}`);
117
+ performanceManager_1.MidwayInitializerPerformanceManager.lifecycleStart(name, lifecycle);
114
118
  const result = await lifecycleInstanceOrList[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
115
119
  if (resultHandler) {
116
120
  resultHandler(result);
117
121
  }
122
+ performanceManager_1.MidwayInitializerPerformanceManager.lifecycleEnd(name, lifecycle);
118
123
  }
119
124
  }
120
125
  }
@@ -127,10 +132,7 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
127
132
  for (const cycle of lifecycleInstanceList) {
128
133
  if (typeof cycle.instance[lifecycle] === 'function') {
129
134
  debug(`[core]: Lifecycle run ${cycle.instance.constructor.name} ${lifecycle}`);
130
- performanceManager_1.MidwayInitializerPerformanceManager.lifecycleStart(cycle.namespace, lifecycle);
131
- const result = await this.applicationContext[lifecycle](cycle.instance[lifecycle].bind(cycle.instance));
132
- performanceManager_1.MidwayInitializerPerformanceManager.lifecycleEnd(cycle.namespace, lifecycle);
133
- return result;
135
+ return await this.applicationContext[lifecycle](cycle.instance[lifecycle].bind(cycle.instance));
134
136
  }
135
137
  }
136
138
  }
@@ -1,28 +1,44 @@
1
1
  import { IMidwayApplication, IMidwayContainer, IMidwayContext, ISimulation } from '../interface';
2
2
  export declare class MidwayMockService {
3
3
  readonly applicationContext: IMidwayContainer;
4
- protected mocks: any[];
5
- protected contextMocks: Array<{
4
+ /**
5
+ * Save class prototype and object property mocks
6
+ */
7
+ protected mocks: Map<string, Array<{
8
+ obj: any;
9
+ key: string;
10
+ descriptor: PropertyDescriptor;
11
+ hasOwnProperty: boolean;
12
+ }>>;
13
+ /**
14
+ * Save context mocks
15
+ */
16
+ protected contextMocks: Map<string, Array<{
6
17
  app: IMidwayApplication;
7
18
  key: string | ((ctx: IMidwayContext) => void);
8
19
  value: any;
9
- }>;
10
- protected cache: Map<any, any>;
20
+ }>>;
21
+ protected cache: Map<string, Map<any, Set<string>>>;
11
22
  protected simulatorList: Array<ISimulation>;
12
23
  constructor(applicationContext: IMidwayContainer);
13
24
  init(): Promise<void>;
25
+ /**
26
+ * Prepare mocks before the service is initialized
27
+ */
14
28
  static prepareMocks: any[];
15
- static mockClassProperty(clzz: new (...args: any[]) => any, propertyName: string, value: any): void;
16
- static mockProperty(obj: new (...args: any[]) => any, key: string, value: any): void;
17
- mockClassProperty(clzz: new (...args: any[]) => any, propertyName: string, value: any): void;
18
- mockProperty(obj: any, key: string, value: any): void;
19
- mockContext(app: IMidwayApplication, key: string | ((ctx: IMidwayContext) => void), value?: PropertyDescriptor | any): void;
20
- restore(): void;
21
- isMocked(obj: any, key: any): any;
29
+ static mockClassProperty(clzz: new (...args: any[]) => any, propertyName: string, value: any, group?: string): void;
30
+ static mockProperty(obj: new (...args: any[]) => any, key: string, value: any, group?: string): void;
31
+ mockClassProperty(clzz: new (...args: any[]) => any, propertyName: string, value: any, group?: string): void;
32
+ mockProperty(obj: any, key: string, value: any, group?: string): void;
33
+ mockContext(app: IMidwayApplication, key: string | ((ctx: IMidwayContext) => void), value?: PropertyDescriptor | any, group?: string): void;
34
+ restore(group?: string): void;
35
+ restoreAll(): void;
36
+ private restoreGroup;
37
+ isMocked(obj: any, key: any, group?: string): boolean;
22
38
  applyContextMocks(app: IMidwayApplication, ctx: IMidwayContext): void;
23
39
  getContextMocksSize(): number;
24
40
  private overridePropertyDescriptor;
25
- initSimulation(): Promise<void>;
41
+ initSimulation(group?: string): Promise<void>;
26
42
  runSimulatorSetup(): Promise<void>;
27
43
  runSimulatorTearDown(): Promise<void>;
28
44
  runSimulatorAppSetup(app: IMidwayApplication): Promise<void>;
@@ -13,91 +13,126 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.MidwayMockService = void 0;
14
14
  const interface_1 = require("../interface");
15
15
  const decorator_1 = require("../decorator");
16
+ const types_1 = require("../util/types");
16
17
  let MidwayMockService = MidwayMockService_1 = class MidwayMockService {
17
18
  constructor(applicationContext) {
18
19
  this.applicationContext = applicationContext;
19
- this.mocks = [];
20
- this.contextMocks = [];
20
+ /**
21
+ * Save class prototype and object property mocks
22
+ */
23
+ this.mocks = new Map();
24
+ /**
25
+ * Save context mocks
26
+ */
27
+ this.contextMocks = new Map();
21
28
  this.cache = new Map();
22
29
  this.simulatorList = [];
23
30
  }
24
31
  async init() {
25
32
  if (MidwayMockService_1.prepareMocks.length > 0) {
26
33
  for (const item of MidwayMockService_1.prepareMocks) {
27
- this.mockProperty(item.obj, item.key, item.value);
34
+ this.mockProperty(item.obj, item.key, item.value, item.group);
28
35
  }
29
36
  MidwayMockService_1.prepareMocks = [];
30
37
  }
31
38
  }
32
- static mockClassProperty(clzz, propertyName, value) {
33
- this.mockProperty(clzz.prototype, propertyName, value);
39
+ static mockClassProperty(clzz, propertyName, value, group = 'default') {
40
+ this.mockProperty(clzz.prototype, propertyName, value, group);
34
41
  }
35
- static mockProperty(obj, key, value) {
42
+ static mockProperty(obj, key, value, group = 'default') {
36
43
  this.prepareMocks.push({
37
44
  obj,
38
45
  key,
39
46
  value,
47
+ group,
40
48
  });
41
49
  }
42
- mockClassProperty(clzz, propertyName, value) {
43
- return this.mockProperty(clzz.prototype, propertyName, value);
50
+ mockClassProperty(clzz, propertyName, value, group = 'default') {
51
+ return this.mockProperty(clzz.prototype, propertyName, value, group);
44
52
  }
45
- mockProperty(obj, key, value) {
53
+ mockProperty(obj, key, value, group = 'default') {
46
54
  // eslint-disable-next-line no-prototype-builtins
47
55
  const hasOwnProperty = obj.hasOwnProperty(key);
48
- this.mocks.push({
56
+ const mockItem = {
49
57
  obj,
50
58
  key,
51
59
  descriptor: Object.getOwnPropertyDescriptor(obj, key),
52
60
  // Make sure the key exists on object not the prototype
53
61
  hasOwnProperty,
54
- });
55
- // Delete the origin key, redefine it below
62
+ };
63
+ if (!this.mocks.has(group)) {
64
+ this.mocks.set(group, []);
65
+ }
66
+ this.mocks.get(group).push(mockItem);
56
67
  if (hasOwnProperty) {
57
68
  delete obj[key];
58
69
  }
59
70
  // Set a flag that checks if it is mocked
60
- let flag = this.cache.get(obj);
71
+ let groupCache = this.cache.get(group);
72
+ if (!groupCache) {
73
+ groupCache = new Map();
74
+ this.cache.set(group, groupCache);
75
+ }
76
+ let flag = groupCache.get(obj);
61
77
  if (!flag) {
62
78
  flag = new Set();
63
- this.cache.set(obj, flag);
79
+ groupCache.set(obj, flag);
64
80
  }
65
81
  flag.add(key);
66
82
  const descriptor = this.overridePropertyDescriptor(value);
67
83
  Object.defineProperty(obj, key, descriptor);
68
84
  }
69
- mockContext(app, key, value) {
70
- this.contextMocks.push({
85
+ mockContext(app, key, value, group = 'default') {
86
+ if (!this.contextMocks.has(group)) {
87
+ this.contextMocks.set(group, []);
88
+ }
89
+ this.contextMocks.get(group).push({
71
90
  app,
72
91
  key,
73
92
  value,
74
93
  });
75
94
  }
76
- restore() {
77
- for (let i = this.mocks.length - 1; i >= 0; i--) {
78
- const m = this.mocks[i];
95
+ restore(group = 'default') {
96
+ this.restoreGroup(group);
97
+ }
98
+ restoreAll() {
99
+ const groups = new Set([
100
+ ...this.mocks.keys(),
101
+ ...this.contextMocks.keys(),
102
+ ...this.cache.keys(),
103
+ ]);
104
+ for (const group of groups) {
105
+ this.restoreGroup(group);
106
+ }
107
+ this.simulatorList = [];
108
+ }
109
+ restoreGroup(group) {
110
+ const groupMocks = this.mocks.get(group) || [];
111
+ for (let i = groupMocks.length - 1; i >= 0; i--) {
112
+ const m = groupMocks[i];
79
113
  if (!m.hasOwnProperty) {
80
- // Delete the mock key, use key on the prototype
81
114
  delete m.obj[m.key];
82
115
  }
83
116
  else {
84
- // Redefine the origin key instead of the mock key
85
117
  Object.defineProperty(m.obj, m.key, m.descriptor);
86
118
  }
87
119
  }
88
- this.mocks = [];
89
- this.contextMocks = [];
90
- this.cache.clear();
91
- this.simulatorList = [];
92
- MidwayMockService_1.prepareMocks = [];
93
- }
94
- isMocked(obj, key) {
95
- const flag = this.cache.get(obj);
120
+ this.mocks.delete(group);
121
+ this.contextMocks.delete(group);
122
+ this.cache.delete(group);
123
+ this.simulatorList = this.simulatorList.filter(sim => sim['group'] !== group);
124
+ }
125
+ isMocked(obj, key, group = 'default') {
126
+ if ((0, types_1.isClass)(obj)) {
127
+ obj = obj.prototype;
128
+ }
129
+ const groupCache = this.cache.get(group);
130
+ const flag = groupCache ? groupCache.get(obj) : undefined;
96
131
  return flag ? flag.has(key) : false;
97
132
  }
98
133
  applyContextMocks(app, ctx) {
99
- if (this.contextMocks.length > 0) {
100
- for (const mockItem of this.contextMocks) {
134
+ for (const [, groupMocks] of this.contextMocks) {
135
+ for (const mockItem of groupMocks) {
101
136
  if (mockItem.app === app) {
102
137
  const descriptor = this.overridePropertyDescriptor(mockItem.value);
103
138
  if (typeof mockItem.key === 'string') {
@@ -111,7 +146,7 @@ let MidwayMockService = MidwayMockService_1 = class MidwayMockService {
111
146
  }
112
147
  }
113
148
  getContextMocksSize() {
114
- return this.contextMocks.length;
149
+ return Array.from(this.contextMocks.values()).reduce((sum, group) => sum + group.length, 0);
115
150
  }
116
151
  overridePropertyDescriptor(value) {
117
152
  const descriptor = {
@@ -130,11 +165,12 @@ let MidwayMockService = MidwayMockService_1 = class MidwayMockService {
130
165
  }
131
166
  return descriptor;
132
167
  }
133
- async initSimulation() {
168
+ async initSimulation(group = 'default') {
134
169
  const simulationModule = (0, decorator_1.listModule)(decorator_1.MOCK_KEY);
135
170
  for (const module of simulationModule) {
136
171
  const instance = await this.applicationContext.getAsync(module);
137
172
  if (await instance.enableCondition()) {
173
+ instance['group'] = group;
138
174
  this.simulatorList.push(instance);
139
175
  }
140
176
  }
@@ -182,6 +218,9 @@ let MidwayMockService = MidwayMockService_1 = class MidwayMockService {
182
218
  }
183
219
  }
184
220
  };
221
+ /**
222
+ * Prepare mocks before the service is initialized
223
+ */
185
224
  MidwayMockService.prepareMocks = [];
186
225
  __decorate([
187
226
  (0, decorator_1.Init)(),
@@ -194,7 +233,7 @@ __decorate([
194
233
  __metadata("design:type", Function),
195
234
  __metadata("design:paramtypes", []),
196
235
  __metadata("design:returntype", void 0)
197
- ], MidwayMockService.prototype, "restore", null);
236
+ ], MidwayMockService.prototype, "restoreAll", null);
198
237
  MidwayMockService = MidwayMockService_1 = __decorate([
199
238
  (0, decorator_1.Provide)(),
200
239
  (0, decorator_1.Scope)(interface_1.ScopeEnum.Singleton),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.19.0-beta.1",
3
+ "version": "3.19.0",
4
4
  "description": "midway core",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -43,5 +43,5 @@
43
43
  "engines": {
44
44
  "node": ">=12"
45
45
  },
46
- "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
46
+ "gitHead": "437e92d9375b0e375f83aa363f3e6a60187c7109"
47
47
  }