blob: 24a075e18a870eabcc5fd2c9e4dea62ede57c13f (
plain)
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
|
export class Resolver {
constructor(factory) {
this.factory = factory;
}
resolveWith(container) {
if (this.isConstructor()) {
return this.resolveDependenciesUsing(container);
}
else {
return this.factory(container);
}
}
parseConstructor(func) {
let code = func.toString();
let regex = /function ([a-zA-Z]*)\((.*)\) *\{/;
return code.match(regex);
}
isConstructor() {
return this.parseConstructor(this.factory)[1] != '';
}
resolveDependenciesUsing(container) {
let ctor = this.parseConstructor(this.factory);
console.log(`Building: ${ctor[1]}`);
let parameters = ctor.slice(2)[0].split(',').filter(Boolean);
let dependencies = parameters.map((parameter) => {
return container.resolve(parameter.trim());
});
return new this.factory(...dependencies);
}
}
export class Registration {
constructor(factory) {
this.factory = factory;
}
create(container) {
return new Resolver(this.factory).resolveWith(container);
}
asSingleton() {
let originalFactory = this.factory;
let item = null;
this.factory = (container) => {
if (item == null) {
item = new Resolver(originalFactory).resolveWith(container);
}
return item;
};
}
}
export default class Registry {
constructor() {
this.registrations = {};
}
register(key, factory) {
if (this.registrations[key] == undefined) {
this.registrations[key] = [];
}
let registration = new Registration(factory);
this.registrations[key].push(registration);
return registration;
}
isRegistered(key) {
return this.registrations.hasOwnProperty(key);
}
resolve(key) {
if (!this.isRegistered(key)) {
throw `"${key}" is not registered`;
}
try {
let registration = this.registrations[key][0];
return registration.create(this);
} catch(error) {
console.error(`ERROR: Could not resolve "${key}" ${error}`);
console.log("REGISTERED:");
console.log(this.registrations);
throw error;
}
}
resolveAll(key) {
return this.registrations[key].map(registration => registration.create(this));
}
}
|