-
Notifications
You must be signed in to change notification settings - Fork 567
/
loader.ts
91 lines (76 loc) · 2.4 KB
/
loader.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
import * as path from 'path';
import { MidwayContainer } from './container';
import { MidwayRequestContainer } from './requestContainer';
export class ContainerLoader {
baseDir;
pluginContext;
applicationContext;
requestContext;
isTsMode;
constructor({baseDir, isTsMode = true}) {
this.baseDir = baseDir;
this.isTsMode = isTsMode;
}
initialize() {
this.pluginContext = new MidwayContainer();
this.applicationContext = new MidwayContainer(this.baseDir);
this.requestContext = new MidwayRequestContainer(this.applicationContext);
// put requestContext to applicationContext
this.applicationContext.registerObject('requestContext', this.requestContext);
this.applicationContext.registerObject('baseDir', this.baseDir);
this.applicationContext.registerObject('isTsMode', this.isTsMode);
}
getApplicationContext() {
return this.applicationContext;
}
getPluginContext() {
return this.pluginContext;
}
getRequestContext() {
return this.requestContext;
}
registerAllHook(hookKey, hookHandler) {
this.registerApplicationHook(hookKey, hookHandler);
this.registerRequestHook(hookKey, hookHandler);
}
registerApplicationHook(hookKey, hookHandler) {
this.applicationContext.registerDataHandler(hookKey, hookHandler);
}
registerRequestHook(hookKey, hookHandler) {
this.requestContext.registerDataHandler(hookKey, hookHandler);
}
loadDirectory(loadOpts: {
loadDir?: string[];
disableAutoLoad?: boolean;
pattern?: string;
ignore?: string;
configLocations?: string[];
} = {}) {
if (!this.isTsMode && loadOpts.disableAutoLoad === undefined) {
// disable auto load in js mode by default
loadOpts.disableAutoLoad = true;
}
// 如果没有关闭autoLoad 则进行load
if (!loadOpts.disableAutoLoad) {
const defaultLoadDir = this.isTsMode ? [this.baseDir] : ['app', 'lib'];
this.applicationContext.load({
loadDir: (loadOpts.loadDir || defaultLoadDir).map(dir => {
return this.buildLoadDir(dir);
}),
pattern: loadOpts.pattern,
ignore: loadOpts.ignore
});
}
}
async refresh() {
await this.pluginContext.ready();
await this.applicationContext.ready();
await this.requestContext.ready();
}
private buildLoadDir(dir) {
if (!path.isAbsolute(dir)) {
return path.join(this.baseDir, dir);
}
return dir;
}
}