/
container.ts
421 lines (366 loc) · 11.8 KB
/
container.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import { CLASS_KEY_CONSTRUCTOR, CONFIG_KEY, LOGGER_KEY, PLUGIN_KEY } from '@midwayjs/decorator';
import {
Autowire,
Container,
getClassMetadata,
getObjectDefinition,
getProviderId,
IApplicationContext,
IContainer,
IManagedInstance,
IManagedParser,
IManagedResolver,
IObjectDefinition,
IObjectDefinitionParser,
IParserContext,
ObjectDefinitionOptions,
ObjectIdentifier,
Scope,
ScopeEnum,
XmlObjectDefinition
} from 'injection';
import * as is from 'is-type-of';
import { FUNCTION_INJECT_KEY, MidwayHandlerKey } from './constant';
import { run } from '@midwayjs/glob';
const graphviz = require('graphviz');
const camelcase = require('camelcase');
const debug = require('debug')('midway:container');
const CONTROLLERS = 'controllers';
const MIDDLEWARES = 'middlewares';
const TYPE_LOGGER = 'logger';
const TYPE_PLUGIN = 'plugin';
interface FrameworkDecoratorMetadata {
key: string;
propertyName: string;
}
class BaseParser {
container: MidwayContainer;
constructor(container: MidwayContainer) {
this.container = container;
}
}
/**
* 用于xml解析扩展
* <controllers />
*/
class ControllerDefinitionParser extends BaseParser implements IObjectDefinitionParser {
readonly name: string = CONTROLLERS;
parse(ele: Element, context: IParserContext): IObjectDefinition {
const definition = new XmlObjectDefinition(ele);
context.parser.parseElementNodes(definition, ele, context);
this.container.controllersIds.push(definition.id);
return definition;
}
}
/**
* 用于xml解析扩展
* <middlewares />
*/
class MiddlewareDefinitionParser extends BaseParser implements IObjectDefinitionParser {
readonly name: string = MIDDLEWARES;
parse(ele: Element, context: IParserContext): IObjectDefinition {
const definition = new XmlObjectDefinition(ele);
context.parser.parseElementNodes(definition, ele, context);
this.container.middlewaresIds.push(definition.id);
return definition;
}
}
class ManagedLogger implements IManagedInstance {
type = TYPE_LOGGER;
name: string;
}
class LoggerParser implements IManagedParser {
get name(): string {
return TYPE_LOGGER;
}
parse(ele: Element, context: IParserContext): IManagedInstance {
const log = new ManagedLogger();
log.name = ele.getAttribute('name').trim();
return log;
}
}
class LoggerResolver implements IManagedResolver {
private container: MidwayContainer;
constructor(container: MidwayContainer) {
this.container = container;
}
get type(): string {
return TYPE_LOGGER;
}
resolve(managed: IManagedInstance): any {
const log: ManagedLogger = managed as ManagedLogger;
if (log.name) {
return this.container.findHandlerHook(MidwayHandlerKey.LOGGER)(log.name);
}
return this.container.findHandlerHook(MidwayHandlerKey.LOGGER)(log.type);
}
async resolveAsync(managed: IManagedInstance): Promise<any> {
return this.resolve(managed);
}
}
class ManagedPlugin implements IManagedInstance {
type = TYPE_PLUGIN;
name: string;
}
class PluginParser implements IManagedParser {
get name(): string {
return TYPE_PLUGIN;
}
parse(ele: Element, context: IParserContext): IManagedInstance {
const plugin = new ManagedPlugin();
plugin.name = ele.getAttribute('name').trim();
return plugin;
}
}
class PluginResolver implements IManagedResolver {
private container: MidwayContainer;
constructor(container: MidwayContainer) {
this.container = container;
}
get type(): string {
return TYPE_PLUGIN;
}
resolve(managed: IManagedInstance): any {
const p = managed as ManagedPlugin;
return this.container.findHandlerHook(MidwayHandlerKey.PLUGIN)(p.name);
}
async resolveAsync(managed: IManagedInstance): Promise<any> {
return this.resolve(managed);
}
}
export class MidwayContainer extends Container implements IContainer {
controllersIds: string[] = [];
middlewaresIds: string[] = [];
handlerMap: Map<string, (handlerKey: string, instance?: any) => any>;
// 仅仅用于兼容requestContainer的ctx
ctx = {};
isTsMode;
constructor(baseDir: string = process.cwd(), parent: IApplicationContext = undefined, isTsMode = true) {
super(baseDir, parent);
this.isTsMode = isTsMode;
}
init(): void {
this.handlerMap = new Map();
super.init();
if (!this.isTsMode) {
// xml扩展 <logger name=""/> <plugin name="hsfclient"/>
this.parser.objectElementParser.registerParser(new LoggerParser());
this.getManagedResolverFactory().registerResolver(new LoggerResolver(this));
this.parser.objectElementParser.registerParser(new PluginParser());
this.getManagedResolverFactory().registerResolver(new PluginResolver(this));
this.parser.registerParser(new ControllerDefinitionParser(this));
this.parser.registerParser(new MiddlewareDefinitionParser(this));
}
this.registerEachCreatedHook();
// 防止直接从applicationContext.getAsync or get对象实例时依赖当前上下文信息出错
// ctx is in requestContainer
this.registerObject('ctx', this.ctx);
}
/**
* update current context in applicationContext
* for mock and other case
* @param ctx ctx
* @deprecated
*/
updateContext(ctx) {
this.ctx = Object.assign({}, ctx || {});
}
/**
* load directory and traverse file to find bind class
* @param opts
*/
load(opts: {
loadDir: string | string[];
pattern?: string | string[];
ignore?: string | string[];
}) {
const loadDirs = [].concat(opts.loadDir || []);
// TODO set 去重
for (const dir of loadDirs) {
const fileResults = run(['**/**.ts', '**/**.tsx', '**/**.js'].concat(opts.pattern || []), {
cwd: dir,
ignore: [
'**/**.d.ts',
'**/logs/**',
'**/run/**',
'**/public/**',
'**/view/**',
'**/views/**'
].concat(opts.ignore || []),
});
for (const file of fileResults) {
debug(`binding file => ${file}`);
const exports = require(file);
this.bindClass(exports);
}
}
}
bindClass(exports) {
if (is.class(exports) || is.function(exports)) {
this.bindModule(exports);
} else {
for (const m in exports) {
const module = exports[m];
if (is.class(module) || is.function(module)) {
this.bindModule(module);
}
}
}
}
protected bindModule(module) {
if (is.class(module)) {
const providerId = getProviderId(module);
if (providerId) {
this.bind(providerId, module);
} else {
if (!this.isTsMode) {
// inject by name in js
this.bind(camelcase(module.name), module);
}
}
} else {
const info: {
id: ObjectIdentifier,
provider: (context?: IApplicationContext) => any,
scope?: Scope,
isAutowire?: boolean
} = module[FUNCTION_INJECT_KEY];
if (info && info.id) {
if (!info.scope) {
info.scope = ScopeEnum.Request;
}
this.bind(info.id, module, {
scope: info.scope,
isAutowire: info.isAutowire
});
}
}
}
createChild(): IContainer {
const child = new Container();
child.parent = this;
return child;
}
protected registerEachCreatedHook() {
// register constructor inject
this.beforeEachCreated((target, constructorArgs, context) => {
let constructorMetaData;
try {
constructorMetaData = getClassMetadata(CLASS_KEY_CONSTRUCTOR, target);
} catch (e) {
debug(`beforeEachCreated error ${e.stack}`);
}
// lack of field
if (constructorMetaData && constructorArgs) {
for (const idx in constructorMetaData) {
const index = parseInt(idx, 10);
const propertyMeta = constructorMetaData[index];
let result;
switch (propertyMeta.type) {
case 'config':
result = this.findHandlerHook(MidwayHandlerKey.CONFIG)(propertyMeta.key);
break;
case 'logger':
result = this.findHandlerHook(MidwayHandlerKey.LOGGER)(propertyMeta.key);
break;
case 'plugin':
result = this.findHandlerHook(MidwayHandlerKey.PLUGIN)(propertyMeta.key);
break;
}
constructorArgs[index] = result;
}
}
});
// register property inject
this.afterEachCreated((instance, context, definition) => {
// 处理配置装饰器
const configSetterProps: FrameworkDecoratorMetadata[] = getClassMetadata(CONFIG_KEY, instance);
this.defineGetterPropertyValue(configSetterProps, instance, this.findHandlerHook(MidwayHandlerKey.CONFIG));
// 处理插件装饰器
const pluginSetterProps: FrameworkDecoratorMetadata[] = getClassMetadata(PLUGIN_KEY, instance);
this.defineGetterPropertyValue(pluginSetterProps, instance, this.findHandlerHook(MidwayHandlerKey.PLUGIN));
// 处理日志装饰器
const loggerSetterProps: FrameworkDecoratorMetadata[] = getClassMetadata(LOGGER_KEY, instance);
this.defineGetterPropertyValue(loggerSetterProps, instance, this.findHandlerHook(MidwayHandlerKey.LOGGER));
// 表示非ts annotation模式
if (!this.isTsMode && !pluginSetterProps && !loggerSetterProps && definition.isAutowire()) {
// this.$$xxx = null; 用来注入config
// this.$xxx = null; 用来注入 logger 或者 插件
Autowire.patchDollar(instance, context, (key: string) => {
if (key[0] === '$') {
return this.findHandlerHook(MidwayHandlerKey.CONFIG)(key.slice(1));
}
try {
const v = this.findHandlerHook(MidwayHandlerKey.PLUGIN)(key);
if (v) {
return v;
}
} catch (e) {
}
return this.findHandlerHook(MidwayHandlerKey.LOGGER)(key);
});
}
});
}
/**
* binding getter method for decorator
*
* @param setterProps
* @param instance
* @param getterHandler
*/
private defineGetterPropertyValue(setterProps: FrameworkDecoratorMetadata[], instance, getterHandler) {
if (setterProps && getterHandler) {
for (const prop of setterProps) {
if (prop.propertyName) {
Object.defineProperty(instance, prop.propertyName, {
get: () => getterHandler(prop.key, instance),
configurable: false,
enumerable: true
});
}
}
}
}
registerDataHandler(handlerType: string, handler: (handlerKey) => any) {
this.handlerMap.set(handlerType, handler);
}
registerCustomBinding(objectDefinition, target) {
super.registerCustomBinding(objectDefinition, target);
// Override the default scope to request
const objDefOptions: ObjectDefinitionOptions = getObjectDefinition(target);
if (objDefOptions && !objDefOptions.scope) {
debug(`register @scope to default value(request), id=${objectDefinition.id}`);
objectDefinition.scope = ScopeEnum.Request;
}
}
dumpDependency() {
const g = graphviz.digraph('G');
for (const [id, module] of this.dependencyMap.entries()) {
g.addNode(id, {label: `${id}(${module.name})\nscope:${module.scope}`, fontsize: '10'});
module.properties.forEach((depId) => {
g.addEdge(id, depId, {label: `properties`, fontsize: '8'});
});
module.constructorArgs.forEach((depId) => {
g.addEdge(id, depId, {label: 'constructor', fontsize: '8'});
});
}
try {
return g.to_dot();
} catch (err) {
console.error('generate injection dependency tree fail, err = ', err.message);
}
}
/**
* get hook from current map or parent map
* @param hookKey
*/
findHandlerHook(hookKey: string) {
if (this.handlerMap.has(hookKey)) {
return this.handlerMap.get(hookKey);
}
if (this.parent) {
return (this.parent as MidwayContainer).findHandlerHook(hookKey);
}
}
}