-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (59 loc) · 1.62 KB
/
index.js
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
const container = (function() {
let registry = {};
let booted = false;
const solve = function(id) {
if (!(id in registry)) {
throw Error(`The service ${id} was not registered`);
}
if (registry[id].target) {
return registry[id].target;
}
if (registry[id].dependencies.length === 0) {
registry[id].target = registry[id].internal
? require(registry[id].path)()
: require(registry[id].path);
return registry[id].target;
}
const solvedDependencies = registry[id].dependencies.map(function(
dependency
) {
return solve(dependency);
});
registry[id].target = require(registry[id].path)(...solvedDependencies);
return registry[id].target;
};
const trimLeadingSlash = function(path) {
return path.replace(/\/+$/, '');
};
return {
register: function(arr, rootDir) {
if (booted) {
throw Error(
'The container is already booted. You cannot register services anymore'
);
}
if (!rootDir) {
throw Error(
'rootDir for internal services must be supplied as second argument'
);
}
rootDir = trimLeadingSlash(rootDir);
for (let { id, path, dependencies = [] } of arr) {
registry = {
...registry,
[id]: {
internal: path.startsWith('./'),
path: path.startsWith('./') ? `${rootDir}/${path}` : path,
dependencies: dependencies,
target: null
}
};
}
},
get: function(id) {
booted = true;
return solve(id);
}
};
})();
module.exports = container;