1
|
|
|
/** |
2
|
|
|
* An utility class to manage services. |
3
|
|
|
* You can define your own services, share instances between components and create |
4
|
|
|
* new instances when necessaru |
5
|
|
|
* |
6
|
|
|
* @class ServicesContainer |
7
|
|
|
*/ |
8
|
|
|
class ServicesContainer { |
9
|
|
|
/** |
10
|
|
|
* Creates an instance of ServicesContainer. |
11
|
|
|
* |
12
|
|
|
* |
13
|
|
|
* @memberOf ServicesContainer |
14
|
|
|
*/ |
15
|
|
|
constructor() { |
16
|
1 |
|
this._instances = {}; |
17
|
1 |
|
this._map = {}; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Register new services. |
22
|
|
|
* @param {String} serviceName name of the service (how clients will use it) |
23
|
|
|
* @param {Class|Function} service the class/constructor of the service |
24
|
|
|
*/ |
25
|
|
|
define(serviceName, service) { |
26
|
2 |
|
this._map[serviceName] = service; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Same as define |
31
|
|
|
* @see ServicesContainer.define |
32
|
|
|
*/ |
33
|
|
|
register(serviceName, service) { |
34
|
2 |
|
this.define(serviceName, service); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Register an instance of a service. If you only set the instance but not |
39
|
|
|
* the constructor (with the define method) this service will be like an singleton. |
40
|
|
|
* Nobody will be able to create an new instance of the service via ServicesContainer |
41
|
|
|
* |
42
|
|
|
* @param {String} serviceName |
43
|
|
|
* @param {Object} instance |
44
|
|
|
*/ |
45
|
|
|
setInstance(serviceName, instance) { |
46
|
3 |
|
this._instances[serviceName] = instance; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Get an instance of a service. If the instance doens't exists yet it will |
51
|
|
|
* instantiate it and return |
52
|
|
|
* @param {String} serviceName |
53
|
|
|
* @returns {Object} |
54
|
|
|
*/ |
55
|
|
|
get(serviceName) { |
56
|
10 |
|
if (!this._instances.hasOwnProperty(serviceName)) { |
57
|
3 |
|
this.setInstance(serviceName, this.getNewInstance(serviceName)); |
58
|
|
|
} |
59
|
|
|
|
60
|
9 |
|
return this._instances[serviceName]; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Get a new instance of a service. Note that if you do not provide an constructor/class, |
65
|
|
|
* this method will fail |
66
|
|
|
* @param {String} serviceName |
67
|
|
|
*/ |
68
|
|
|
getNewInstance(serviceName) { |
69
|
5 |
|
if (this._instances.hasOwnProperty(serviceName) && !this._map.hasOwnProperty(serviceName)) { |
70
|
1 |
|
throw new Error(`Service ${serviceName} is an singleton, you cannot create a new instance`); |
71
|
|
|
} |
72
|
|
|
|
73
|
4 |
|
if (!this._map.hasOwnProperty(serviceName)) { |
74
|
1 |
|
throw new Error(`Service ${serviceName} not found`); |
75
|
|
|
} |
76
|
|
|
|
77
|
3 |
|
return new this._map[serviceName](); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
export default ServicesContainer; |
82
|
|
|
|