Test Failed
Pull Request — master (#2)
by Luís
03:32 queued 01:49
created

src/js/core/ServicesContainer.js   A

Size

Lines of Code 66

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
nc 1
dl 0
loc 66
rs 10
c 2
b 0
f 1
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A ServicesContainer.js ➔ ??? 0 4 1
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
        this._instances = {};
17
        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
        this._map[serviceName] = service;
27
    }
28
29
    /**
30
     * Register an instance of a service. If you only set the instance but not
31
     * the constructor (with the define method) this service will be like an singleton.
32
     * Nobody will be able to create an new instance of the service via ServicesContainer
33
     * 
34
     * @param {String} serviceName
35
     * @param {Object} instance
36
     */
37
    setInstance(serviceName, instance) {
38
        this._instances[serviceName] = instance;
39
    }
40
41
    /**
42
     * Get an instance of a service. If the instance doens't exists yet it will
43
     * instantiate it and return
44
     * @param {String} serviceName
45
     * @returns {Object}
46
     */
47
    get(serviceName) {
48
        if (!this._instances.hasOwnProperty(serviceName)) {
49
            this.setInstance(serviceName, this.getNewInstance(serviceName));
50
        }
51
52
        return this._instances[serviceName];
53
    }
54
55
    /**
56
     * Get a new instance of a service. Note that if you do not provide an constructor/class,
57
     * this method will fail
58
     * @param {String} serviceName
59
     */
60
    getNewInstance(serviceName) {
61
        if (this._instances.hasOwnProperty(serviceName) && !this._map.hasOwnProperty(serviceName)) {
62
            throw new Error(`Service ${serviceName} is an singleton, you cannot create a new instance`);
63
        }
64
65
        if (!this._map.hasOwnProperty(serviceName)) {
66
            throw new Error(`Service ${serviceName} not found`);
67
        }
68
69
        return new this._map[serviceName]();
70
    }
71
}
72
73
export default ServicesContainer;
74