@midwayjs/core 3.19.0-beta.2 → 3.20.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.
package/README.md CHANGED
@@ -9,4 +9,4 @@ Document: [https://midwayjs.org](https://midwayjs.org)
9
9
 
10
10
  ## License
11
11
 
12
- [MIT]((http://github.com/midwayjs/midway/blob/master/LICENSE))
12
+ [MIT]((https://github.com/midwayjs/midway/blob/master/LICENSE))
@@ -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 => {
@@ -18,6 +18,7 @@ export declare class MidwayPerformanceManager {
18
18
  disconnect(): void;
19
19
  clean(): void;
20
20
  static cleanAll(): void;
21
+ static getInitialPerformanceEntries(): any[];
21
22
  }
22
23
  export declare class MidwayInitializerPerformanceManager {
23
24
  static MEASURE_KEYS: {
@@ -28,10 +29,9 @@ export declare class MidwayInitializerPerformanceManager {
28
29
  CONFIG_LOAD: string;
29
30
  LOGGER_PREPARE: string;
30
31
  FRAMEWORK_PREPARE: string;
31
- CUSTOM_FRAMEWORK_INITIALIZE: string;
32
- CUSTOM_FRAMEWORK_RUN: 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;
@@ -80,6 +80,15 @@ class MidwayPerformanceManager {
80
80
  this.instances.forEach(instance => instance.clean());
81
81
  this.instances.clear();
82
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
+ }
83
92
  }
84
93
  exports.MidwayPerformanceManager = MidwayPerformanceManager;
85
94
  MidwayPerformanceManager.instances = new Map();
@@ -96,22 +105,22 @@ class MidwayInitializerPerformanceManager {
96
105
  manager.markEnd(key);
97
106
  }
98
107
  static frameworkInitializeStart(frameworkName) {
99
- this.markStart(`${this.MEASURE_KEYS.CUSTOM_FRAMEWORK_INITIALIZE}:${frameworkName}`);
108
+ this.markStart(`${this.MEASURE_KEYS.FRAMEWORK_INITIALIZE}:${frameworkName}`);
100
109
  }
101
110
  static frameworkInitializeEnd(frameworkName) {
102
- this.markEnd(`${this.MEASURE_KEYS.CUSTOM_FRAMEWORK_INITIALIZE}:${frameworkName}`);
111
+ this.markEnd(`${this.MEASURE_KEYS.FRAMEWORK_INITIALIZE}:${frameworkName}`);
103
112
  }
104
113
  static frameworkRunStart(frameworkName) {
105
- this.markStart(`${this.MEASURE_KEYS.CUSTOM_FRAMEWORK_RUN}:${frameworkName}`);
114
+ this.markStart(`${this.MEASURE_KEYS.FRAMEWORK_RUN}:${frameworkName}`);
106
115
  }
107
116
  static frameworkRunEnd(frameworkName) {
108
- this.markEnd(`${this.MEASURE_KEYS.CUSTOM_FRAMEWORK_RUN}:${frameworkName}`);
117
+ this.markEnd(`${this.MEASURE_KEYS.FRAMEWORK_RUN}:${frameworkName}`);
109
118
  }
110
119
  static lifecycleStart(namespace, lifecycleName) {
111
- this.markStart(`${this.MEASURE_KEYS.CUSTOM_LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
120
+ this.markStart(`${this.MEASURE_KEYS.LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
112
121
  }
113
122
  static lifecycleEnd(namespace, lifecycleName) {
114
- this.markEnd(`${this.MEASURE_KEYS.CUSTOM_LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
123
+ this.markEnd(`${this.MEASURE_KEYS.LIFECYCLE_PREPARE}:${namespace}:${lifecycleName}`);
115
124
  }
116
125
  }
117
126
  exports.MidwayInitializerPerformanceManager = MidwayInitializerPerformanceManager;
@@ -123,10 +132,9 @@ MidwayInitializerPerformanceManager.MEASURE_KEYS = {
123
132
  CONFIG_LOAD: 'ConfigLoad',
124
133
  LOGGER_PREPARE: 'LoggerPrepare',
125
134
  FRAMEWORK_PREPARE: 'FrameworkPrepare',
126
- CUSTOM_FRAMEWORK_INITIALIZE: 'CustomFrameworkInitialize',
127
- CUSTOM_FRAMEWORK_RUN: 'CustomFrameworkRun',
135
+ FRAMEWORK_INITIALIZE: 'FrameworkInitialize',
136
+ FRAMEWORK_RUN: 'FrameworkRun',
128
137
  LIFECYCLE_PREPARE: 'LifecyclePrepare',
129
- CUSTOM_LIFECYCLE_PREPARE: 'CustomLifecyclePrepare',
130
138
  PRELOAD_MODULE_PREPARE: 'PreloadModulePrepare',
131
139
  };
132
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
@@ -426,7 +426,9 @@ export type DataSourceManagerConfigOption<OPTIONS, ENTITY_CONFIG_KEY extends str
426
426
  dataSource?: {
427
427
  [key: string]: PowerPartial<{
428
428
  [keyName in ENTITY_CONFIG_KEY]: any[];
429
- }> & OPTIONS;
429
+ }> & OPTIONS & {
430
+ customDataSourceClass?: any;
431
+ };
430
432
  };
431
433
  } & CreateDataSourceInstanceOptions;
432
434
  type ConfigType<T> = T extends (...args: any[]) => any ? Writable<PowerPartial<ReturnType<T>>> : Writable<PowerPartial<T>>;
@@ -1011,5 +1013,6 @@ export interface ServerSendEventStreamOptions<CTX extends IMidwayContext> {
1011
1013
  closeEvent?: string;
1012
1014
  tpl?: (data: ServerSendEventMessage, ctx: CTX) => ServerSendEventMessage;
1013
1015
  }
1016
+ export type ClassType<T = any> = new (...args: any[]) => T;
1014
1017
  export {};
1015
1018
  //# sourceMappingURL=interface.d.ts.map
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import { IMidwayContext } from '../interface';
3
4
  export declare class ServerResponse<CTX extends IMidwayContext = IMidwayContext> {
4
5
  protected readonly ctx: any;
@@ -1,5 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
+ /// <reference types="node" />
3
4
  import { IMidwayContext, ServerSendEventMessage, ServerSendEventStreamOptions, ServerStreamOptions } from '../interface';
4
5
  import { ServerResponse } from './base';
5
6
  import { ServerSendEventStream } from './sse';
@@ -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)(),
@@ -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),
@@ -1,6 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
3
  /// <reference types="node" />
4
+ /// <reference types="node" />
4
5
  import http = require('http');
5
6
  import https = require('https');
6
7
  export type HttpClientMimeType = 'text' | 'json' | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.19.0-beta.2",
3
+ "version": "3.20.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": "5bf838ec6054f6e1e983664b0456a975db795932"
47
47
  }