@midwayjs/core 3.0.0-alpha.36 → 3.0.0-alpha.42

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.
@@ -107,6 +107,16 @@ class BaseFramework {
107
107
  await this.initializeLogger(options);
108
108
  }
109
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
+ }
110
120
  // register app
111
121
  this.applicationContext.registerDataHandler(decorator_1.APPLICATION_KEY, (key, meta) => {
112
122
  var _a;
@@ -271,7 +281,7 @@ class BaseFramework {
271
281
  }
272
282
  else {
273
283
  // 普通类写法
274
- const providerId = (0, decorator_1.getProviderUUId)(cycle.target);
284
+ const providerId = (0, decorator_1.getProviderId)(cycle.target);
275
285
  if (this.getApplicationContext().registry.hasDefinition(providerId)) {
276
286
  cycle.instance =
277
287
  await this.getApplicationContext().getAsync(providerId);
@@ -290,7 +300,22 @@ class BaseFramework {
290
300
  }
291
301
  for (const cycle of lifecycleInstanceList) {
292
302
  if (typeof cycle.instance.onReady === 'function') {
293
- await cycle.instance.onReady(this.getApplicationContext(), this.app);
303
+ /**
304
+ * 让组件能正确获取到 bind 之后 registerObject 的对象有三个方法
305
+ * 1、在 load 之后修改 bind,不太可行
306
+ * 2、每次 getAsync 的时候,去掉 namespace,同时还要查找当前全局的变量,性能差
307
+ * 3、一般只会在 onReady 的地方执行 registerObject(否则没有全局的意义),这个取巧的办法就是 onReady 传入一个代理,其中绑定当前的 namespace
308
+ */
309
+ await cycle.instance.onReady(new Proxy(this.getApplicationContext(), {
310
+ get: function (target, prop, receiver) {
311
+ if (prop === 'getCurrentNamespace' && cycle.namespace) {
312
+ return () => {
313
+ return cycle.namespace;
314
+ };
315
+ }
316
+ return Reflect.get(target, prop, receiver);
317
+ },
318
+ }), this.app);
294
319
  }
295
320
  }
296
321
  }
@@ -303,11 +328,20 @@ class BaseFramework {
303
328
  inst = cycle.target;
304
329
  }
305
330
  else {
306
- const providerId = (0, decorator_1.getProviderUUId)(cycle.target);
331
+ const providerId = (0, decorator_1.getProviderId)(cycle.target);
307
332
  inst = await this.applicationContext.getAsync(providerId);
308
333
  }
309
334
  if (inst.onStop && typeof inst.onStop === 'function') {
310
- await inst.onStop(this.getApplicationContext(), this.app);
335
+ await inst.onStop(new Proxy(this.getApplicationContext(), {
336
+ get: function (target, prop, receiver) {
337
+ if (prop === 'getCurrentNamespace' && cycle.namespace) {
338
+ return () => {
339
+ return cycle.namespace;
340
+ };
341
+ }
342
+ return Reflect.get(target, prop, receiver);
343
+ },
344
+ }), this.app);
311
345
  }
312
346
  }
313
347
  }
@@ -1,7 +1,5 @@
1
1
  import 'reflect-metadata';
2
- export interface ReflectResult {
3
- [key: string]: any[];
4
- }
2
+ import { ReflectResult } from '@midwayjs/decorator';
5
3
  /**
6
4
  * 以数组形式返回对象所有 property, 数组第一个元素是距离 o 最近的原型
7
5
  * @param target 对象,class 或者 function
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 基础的ObjectFactory和ApplicationContext实现
3
+ */
4
+ import { ObjectIdentifier } from '@midwayjs/decorator';
5
+ import { IApplicationContext, IObjectDefinition, IObjectDefinitionRegistry, IObjectFactory, ObjectDependencyTree } from '../interface';
6
+ import { ObjectProperties } from '../definitions/properties';
7
+ import { ManagedResolverFactory } from './managedResolverFactory';
8
+ export declare class ObjectDefinitionRegistry extends Map implements IObjectDefinitionRegistry {
9
+ private singletonIds;
10
+ get identifiers(): any[];
11
+ get count(): number;
12
+ getSingletonDefinitionIds(): ObjectIdentifier[];
13
+ getDefinitionByName(name: string): IObjectDefinition[];
14
+ registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition): void;
15
+ getDefinition(identifier: ObjectIdentifier): IObjectDefinition;
16
+ getDefinitionByPath(path: string): IObjectDefinition;
17
+ removeDefinition(identifier: ObjectIdentifier): void;
18
+ hasDefinition(identifier: ObjectIdentifier): boolean;
19
+ clearAll(): void;
20
+ hasObject(identifier: ObjectIdentifier): boolean;
21
+ registerObject(identifier: ObjectIdentifier, target: any): void;
22
+ getObject(identifier: ObjectIdentifier): any;
23
+ }
24
+ export declare class BaseApplicationContext implements IApplicationContext, IObjectFactory {
25
+ protected readied: boolean;
26
+ protected midwayIdentifiers: string[];
27
+ private _resolverFactory;
28
+ private _registry;
29
+ private _props;
30
+ private _dependencyMap;
31
+ baseDir: string;
32
+ parent: IApplicationContext;
33
+ disableConflictCheck: boolean;
34
+ constructor(baseDir?: string, parent?: IApplicationContext);
35
+ get dependencyMap(): Map<string, ObjectDependencyTree>;
36
+ get props(): ObjectProperties;
37
+ get registry(): IObjectDefinitionRegistry;
38
+ set registry(registry: IObjectDefinitionRegistry);
39
+ protected getManagedResolverFactory(): ManagedResolverFactory;
40
+ /**
41
+ * 继承实现时需要调用super
42
+ */
43
+ protected init(): void;
44
+ stop(): Promise<void>;
45
+ ready(): void;
46
+ protected loadDefinitions(): void;
47
+ isAsync(identifier: ObjectIdentifier): boolean;
48
+ get<T>(identifier: {
49
+ new (...args: any[]): T;
50
+ }, args?: any): T;
51
+ get<T>(identifier: ObjectIdentifier, args?: any): T;
52
+ getAsync<T>(identifier: {
53
+ new (...args: any[]): T;
54
+ }, args?: any): Promise<T>;
55
+ getAsync<T>(identifier: ObjectIdentifier, args?: any): Promise<T>;
56
+ get isReady(): boolean;
57
+ /**
58
+ * proxy registry.registerDefinition
59
+ * @param {ObjectIdentifier} identifier
60
+ * @param {IObjectDefinition} definition
61
+ */
62
+ registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition): void;
63
+ /**
64
+ * proxy registry.registerObject
65
+ * @param {ObjectIdentifier} identifier
66
+ * @param target
67
+ */
68
+ registerObject(identifier: ObjectIdentifier, target: any): void;
69
+ /**
70
+ * register handler after instance create
71
+ * @param fn
72
+ */
73
+ afterEachCreated(fn: (ins: any, context: IApplicationContext, definition?: IObjectDefinition) => void): void;
74
+ /**
75
+ * register handler before instance create
76
+ * @param fn
77
+ */
78
+ beforeEachCreated(fn: (Clzz: any, constructorArgs: any[], context: IApplicationContext) => void): void;
79
+ protected createObjectDependencyTree(identifier: any, definition: any): void;
80
+ }
81
+ //# sourceMappingURL=applicationContext.d.ts.map
@@ -0,0 +1,263 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseApplicationContext = exports.ObjectDefinitionRegistry = void 0;
4
+ /**
5
+ * 基础的ObjectFactory和ApplicationContext实现
6
+ */
7
+ const decorator_1 = require("@midwayjs/decorator");
8
+ const properties_1 = require("../definitions/properties");
9
+ const managedResolverFactory_1 = require("./managedResolverFactory");
10
+ const notFoundError_1 = require("../common/notFoundError");
11
+ const util_1 = require("../util/");
12
+ const pathFileUtil_1 = require("../util/pathFileUtil");
13
+ const PREFIX = '_id_default_';
14
+ class ObjectDefinitionRegistry extends Map {
15
+ constructor() {
16
+ super(...arguments);
17
+ this.singletonIds = [];
18
+ }
19
+ get identifiers() {
20
+ const ids = [];
21
+ for (const key of this.keys()) {
22
+ if (key.indexOf(PREFIX) === -1) {
23
+ ids.push(key);
24
+ }
25
+ }
26
+ return ids;
27
+ }
28
+ get count() {
29
+ return this.size;
30
+ }
31
+ getSingletonDefinitionIds() {
32
+ return this.singletonIds;
33
+ }
34
+ getDefinitionByName(name) {
35
+ const definitions = [];
36
+ for (const v of this.values()) {
37
+ const definition = v;
38
+ if (definition.name === name) {
39
+ definitions.push(definition);
40
+ }
41
+ }
42
+ return definitions;
43
+ }
44
+ registerDefinition(identifier, definition) {
45
+ if (definition.isSingletonScope()) {
46
+ this.singletonIds.push(identifier);
47
+ }
48
+ this.set(identifier, definition);
49
+ }
50
+ getDefinition(identifier) {
51
+ return this.get(identifier);
52
+ }
53
+ getDefinitionByPath(path) {
54
+ for (const v of this.values()) {
55
+ const definition = v;
56
+ if (definition.path === path) {
57
+ return definition;
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+ removeDefinition(identifier) {
63
+ this.delete(identifier);
64
+ }
65
+ hasDefinition(identifier) {
66
+ return this.has(identifier);
67
+ }
68
+ clearAll() {
69
+ this.singletonIds = [];
70
+ this.clear();
71
+ }
72
+ hasObject(identifier) {
73
+ return this.has(PREFIX + identifier);
74
+ }
75
+ registerObject(identifier, target) {
76
+ this.set(PREFIX + identifier, target);
77
+ }
78
+ getObject(identifier) {
79
+ return this.get(PREFIX + identifier);
80
+ }
81
+ }
82
+ exports.ObjectDefinitionRegistry = ObjectDefinitionRegistry;
83
+ class BaseApplicationContext {
84
+ constructor(baseDir = '', parent) {
85
+ this.readied = false;
86
+ // 自己内部实现的,可注入的 feature(见 features)
87
+ this.midwayIdentifiers = [];
88
+ this._resolverFactory = null;
89
+ this._registry = null;
90
+ this._props = null;
91
+ this._dependencyMap = null;
92
+ this.baseDir = null;
93
+ this.parent = null;
94
+ this.disableConflictCheck = false;
95
+ this.parent = parent;
96
+ this.baseDir = baseDir;
97
+ this.init();
98
+ }
99
+ get dependencyMap() {
100
+ if (!this._dependencyMap) {
101
+ this._dependencyMap = new Map();
102
+ }
103
+ return this._dependencyMap;
104
+ }
105
+ get props() {
106
+ if (!this._props) {
107
+ this._props = new properties_1.ObjectProperties();
108
+ }
109
+ return this._props;
110
+ }
111
+ get registry() {
112
+ if (!this._registry) {
113
+ this._registry = new ObjectDefinitionRegistry();
114
+ }
115
+ return this._registry;
116
+ }
117
+ set registry(registry) {
118
+ this._registry = registry;
119
+ }
120
+ getManagedResolverFactory() {
121
+ if (!this._resolverFactory) {
122
+ this._resolverFactory = new managedResolverFactory_1.ManagedResolverFactory(this);
123
+ }
124
+ return this._resolverFactory;
125
+ }
126
+ /**
127
+ * 继承实现时需要调用super
128
+ */
129
+ init() { }
130
+ async stop() {
131
+ await this.getManagedResolverFactory().destroyCache();
132
+ this.registry.clearAll();
133
+ this.readied = false;
134
+ }
135
+ ready() {
136
+ this.loadDefinitions();
137
+ this.readied = true;
138
+ }
139
+ loadDefinitions() { }
140
+ isAsync(identifier) {
141
+ if (this.registry.hasDefinition(identifier)) {
142
+ return this.registry.getDefinition(identifier).isAsync();
143
+ }
144
+ return false;
145
+ }
146
+ get(identifier, args) {
147
+ if (!this.readied) {
148
+ this.ready();
149
+ }
150
+ if (typeof identifier !== 'string') {
151
+ identifier = (0, decorator_1.getProviderId)(identifier);
152
+ }
153
+ // 因为在这里拿不到类名, NotFoundError 类的错误信息在 ManagedResolverFactory.ts createAsync 方法中增加错误类名
154
+ identifier = (0, util_1.parsePrefix)(identifier);
155
+ if (this.registry.hasObject(identifier)) {
156
+ return this.registry.getObject(identifier);
157
+ }
158
+ if (this.isAsync(identifier)) {
159
+ throw new Error(`${identifier} must use getAsync`);
160
+ }
161
+ const definition = this.registry.getDefinition(identifier);
162
+ if (!definition && this.parent) {
163
+ if (this.parent.isAsync(identifier)) {
164
+ throw new Error(`${identifier} must use getAsync`);
165
+ }
166
+ return this.parent.get(identifier, args);
167
+ }
168
+ if (!definition) {
169
+ throw new notFoundError_1.NotFoundError(identifier);
170
+ }
171
+ return this.getManagedResolverFactory().create({ definition, args });
172
+ }
173
+ async getAsync(identifier, args) {
174
+ if (!this.readied) {
175
+ this.ready();
176
+ }
177
+ if (typeof identifier !== 'string') {
178
+ identifier = (0, decorator_1.getProviderId)(identifier);
179
+ }
180
+ // 因为在这里拿不到类名, NotFoundError 类的错误信息在 ManagedResolverFactory.ts createAsync 方法中增加错误类名
181
+ identifier = (0, util_1.parsePrefix)(identifier);
182
+ if (this.registry.hasObject(identifier)) {
183
+ return this.registry.getObject(identifier);
184
+ }
185
+ const definition = this.registry.getDefinition(identifier);
186
+ if (!definition && this.parent) {
187
+ return this.parent.getAsync(identifier, args);
188
+ }
189
+ if (!definition) {
190
+ throw new notFoundError_1.NotFoundError(identifier);
191
+ }
192
+ return this.getManagedResolverFactory().createAsync({ definition, args });
193
+ }
194
+ get isReady() {
195
+ return this.readied;
196
+ }
197
+ /**
198
+ * proxy registry.registerDefinition
199
+ * @param {ObjectIdentifier} identifier
200
+ * @param {IObjectDefinition} definition
201
+ */
202
+ registerDefinition(identifier, definition) {
203
+ if (!this.disableConflictCheck && this.registry.hasDefinition(identifier)) {
204
+ const def = this.registry.getDefinition(identifier);
205
+ if (definition.srcPath && def.srcPath) {
206
+ if (!pathFileUtil_1.PathFileUtil.isPathEqual(definition.srcPath, def.srcPath)) {
207
+ throw new Error(`${identifier} path = ${definition.srcPath} already exist (${def.srcPath})!`);
208
+ }
209
+ }
210
+ }
211
+ this.registry.registerDefinition(identifier, definition);
212
+ this.createObjectDependencyTree(identifier, definition);
213
+ }
214
+ /**
215
+ * proxy registry.registerObject
216
+ * @param {ObjectIdentifier} identifier
217
+ * @param target
218
+ */
219
+ registerObject(identifier, target) {
220
+ this.registry.registerObject(identifier, target);
221
+ }
222
+ /**
223
+ * register handler after instance create
224
+ * @param fn
225
+ */
226
+ afterEachCreated(fn) {
227
+ this.getManagedResolverFactory().afterEachCreated(fn);
228
+ }
229
+ /**
230
+ * register handler before instance create
231
+ * @param fn
232
+ */
233
+ beforeEachCreated(fn) {
234
+ this.getManagedResolverFactory().beforeEachCreated(fn);
235
+ }
236
+ createObjectDependencyTree(identifier, definition) {
237
+ if (!this.dependencyMap.has(identifier)) {
238
+ let constructorArgs = definition.constructorArgs || [];
239
+ constructorArgs = constructorArgs
240
+ .map(ref => {
241
+ return ref.name;
242
+ })
243
+ .filter(name => {
244
+ return !!name;
245
+ });
246
+ const properties = (definition.properties &&
247
+ definition.properties.keys().map(key => {
248
+ return definition.properties.get(key).name;
249
+ })) ||
250
+ [];
251
+ this.dependencyMap.set(identifier, {
252
+ name: typeof definition.path !== 'string'
253
+ ? definition.path.name
254
+ : identifier,
255
+ scope: definition.scope,
256
+ constructorArgs,
257
+ properties,
258
+ });
259
+ }
260
+ }
261
+ }
262
+ exports.BaseApplicationContext = BaseApplicationContext;
263
+ //# sourceMappingURL=applicationContext.js.map
@@ -1,15 +1,22 @@
1
1
  /// <reference types="node" />
2
2
  import { ObjectDefinitionOptions, ObjectIdentifier } from '@midwayjs/decorator';
3
3
  import * as util from 'util';
4
- import { IConfigService, IEnvironmentService, IFileDetector, IIdentifierRelationShip, IInformationService, IMidwayContainer, IObjectDefinition, IObjectDefinitionRegistry } from '../interface';
4
+ import { BaseApplicationContext } from './applicationContext';
5
+ import { IConfigService, IEnvironmentService, IFileDetector, IInformationService, IMidwayContainer, IObjectDefinitionMetadata } from '../interface';
5
6
  import { ResolverHandler } from './resolverHandler';
6
- import { ManagedResolverFactory } from './managedResolverFactory';
7
- export declare class MidwayContainer implements IMidwayContainer {
8
- private _resolverFactory;
9
- private _registry;
10
- private _identifierMapping;
11
- parent: IMidwayContainer;
7
+ declare class ContainerConfiguration {
8
+ readonly container: any;
9
+ private namespace;
10
+ constructor(container: any);
11
+ load(module: any): void;
12
+ addImportConfigs(importConfigs: string[]): void;
13
+ addImports(imports?: any[]): void;
14
+ bindConfigurationClass(clzz: any, filePath?: string): void;
15
+ private getConfigurationExport;
16
+ }
17
+ export declare class MidwayContainer extends BaseApplicationContext implements IMidwayContainer {
12
18
  private debugLogger;
19
+ private definitionMetadataList;
13
20
  protected resolverHandler: ResolverHandler;
14
21
  protected ctx: {};
15
22
  protected configService: IConfigService;
@@ -19,19 +26,18 @@ export declare class MidwayContainer implements IMidwayContainer {
19
26
  private fileDetector;
20
27
  private attrMap;
21
28
  private isLoad;
22
- constructor(parent?: IMidwayContainer);
23
- protected init(): void;
24
- get registry(): IObjectDefinitionRegistry;
25
- set registry(registry: IObjectDefinitionRegistry);
26
- get managedResolverFactory(): ManagedResolverFactory;
27
- get identifierMapping(): IIdentifierRelationShip;
28
- protected initService(): void;
29
+ init(): void;
30
+ initService(): void;
29
31
  load(module?: any): void;
30
- protected loadDefinitions(): void;
32
+ loadDefinitions(): void;
33
+ createConfiguration(): ContainerConfiguration;
31
34
  bindClass(exports: any, namespace?: string, filePath?: string): void;
32
35
  bind<T>(target: T, options?: ObjectDefinitionOptions): void;
33
36
  bind<T>(identifier: ObjectIdentifier, target: T, options?: ObjectDefinitionOptions): void;
34
- protected bindModule(module: any, options?: ObjectDefinitionOptions): void;
37
+ protected restoreDefinition(definitionMeta: IObjectDefinitionMetadata): void;
38
+ protected restoreDefinitions(definitionMetadataList: any): void;
39
+ protected getDefinitionMetaList(): any[];
40
+ protected bindModule(module: any, namespace?: string, filePath?: string): void;
35
41
  getDebugLogger(): util.DebugLogger;
36
42
  setFileDetector(fileDetector: IFileDetector): void;
37
43
  createChild(): IMidwayContainer;
@@ -45,34 +51,6 @@ export declare class MidwayContainer implements IMidwayContainer {
45
51
  getResolverHandler(): ResolverHandler;
46
52
  setAttr(key: string, value: any): void;
47
53
  getAttr<T>(key: string): T;
48
- protected getIdentifier(target: any): string;
49
- protected findRegisterObject(identifier: any): any;
50
- protected getManagedResolverFactory(): ManagedResolverFactory;
51
- stop(): Promise<void>;
52
- ready(): Promise<void>;
53
- get<T>(identifier: {
54
- new (...args: any[]): T;
55
- }, args?: any): T;
56
- get<T>(identifier: ObjectIdentifier, args?: any): T;
57
- getAsync<T>(identifier: {
58
- new (...args: any[]): T;
59
- }, args?: any): Promise<T>;
60
- getAsync<T>(identifier: ObjectIdentifier, args?: any): Promise<T>;
61
- /**
62
- * proxy registry.registerObject
63
- * @param {ObjectIdentifier} identifier
64
- * @param target
65
- */
66
- registerObject(identifier: ObjectIdentifier, target: any): void;
67
- /**
68
- * register handler after instance create
69
- * @param fn
70
- */
71
- afterEachCreated(fn: (ins: any, context: IMidwayContainer, definition?: IObjectDefinition) => void): void;
72
- /**
73
- * register handler before instance create
74
- * @param fn
75
- */
76
- beforeEachCreated(fn: (Clzz: any, constructorArgs: any[], context: IMidwayContainer) => void): void;
77
54
  }
55
+ export {};
78
56
  //# sourceMappingURL=container.d.ts.map