This repository has been archived by the owner on Jun 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathObjectContainer.js
713 lines (641 loc) · 22 KB
/
ObjectContainer.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import ns from 'ima/namespace';
ns.namespace('ima');
/**
* The Object Container is an enhanced dependency injector with support for
* aliases and constants, and allowing to reference classes in the application
* namespace by specifying their fully qualified names.
*
* @class ObjectContainer
* @namespace ima
* @module ima
* @requires ima.Namespace
*/
export default class ObjectContainer {
/**
* Initializes the object container.
*
* @constructor
* @method constructor
* @param {ima.Namespace} namespace The namespace container, used to
* access classes and values using their fully qualified names.
*/
constructor(namespace) {
/**
* The namespace container, used to access classes and values using
* their fully qualified names.
*
* @private
* @property _namespace
* @type {ima.Namespace}
*/
this._namespace = namespace;
/**
* Map of bound aliases to their classes and the dependencies bound
* with the alias.
*
* @private
* @property _aliases
* @type {Map<string, Entry<*>>}
*/
this._aliases = new Map();
/**
* Map of constant names to getter function entries for retrieving the
* constant values.
*
* @private
* @property _constants
* @type {Map<string, Entry<function(): *>>}
*/
this._constants = new Map();
/**
* Registry of classes and factory functions to their entries
* specifying their default dependencies.
*
* @private
* @property _registry
* @type {Map<(function(new: *, ...*)|function(...*): *), Entry<*>>}
*/
this._registry = new Map();
/**
* Map of interfaces to entries representing the default implementation
* providers (classes) and their constructor dependencies.
*
* @private
* @property _providers
* @type {Map<function(new: *), Entry<*>>}
*/
this._providers = new Map();
/**
* The number of calling {@linkcode lock()} and {@linkcode unlock()}
* methods.
*
* The {@linkcode lock()} method may be called only if this field is
* {@code 0}, while the {@linkcode unlock()} method may be called only
* if this field is set to {@code 1}.
*
* @private
* @property _lockCounter
* @type {number}
*/
this._lockCounter = 0;
}
/**
* Binds the specified class or factory function and dependencies to the
* specified alias. Binding a class or factory function to an alias allows
* the class or function to be specied as a dependency by specifying the
* alias and creating new instances by referring to the class or function
* by the alias.
*
* Also note that the same class or function may be bound to several
* aliases and each may use different dependencies.
*
* The alias will use the default dependencies bound for the class if no
* dependencies are provided.
*
* @chainable
* @method bind
* @param {string} name Alias name.
* @param {(function(new: T, ...*)|function(...*): T)} classConstructor The
* class constructor or a factory function.
* @param {*[]} [dependencies=[]] The dependencies to pass into the
* constructor or factory function.
* @return {ima.ObjectContainer} This object container.
*/
bind(name, classConstructor, dependencies = []) {
if ($Debug) {
if (this.isLocked()) {
throw new Error(`ima.ObjectContainer:bind Object container ` +
`is locked. You do not have the permission to ` +
`create a new alias named ${name}.`);
}
if (typeof classConstructor !== 'function') {
throw new Error(`ima.ObjectContainer:bind The second ` +
`argument has to be a class constructor function, ` +
`but ${classConstructor} was provided. Fix alias ` +
`${name} for your bind.js file.`);
}
}
if (dependencies.length === 0) {
if (this._registry.has(classConstructor)) {
var registryEntry = this._registry.get(classConstructor);
this._aliases.set(name, registryEntry);
return this;
}
if (this._providers.has(classConstructor)) {
var providerEntry = this._providers.get(classConstructor);
this._aliases.set(name, providerEntry);
return this;
}
}
var newEntry = this._createEntry(classConstructor, dependencies);
this._aliases.set(name, newEntry);
return this;
}
/**
* Defines a new constant registered with this object container. Note that
* this is the only way of passing {@code string} values to constructors
* because the object container treats strings as class, interface, alias
* or constant names.
*
* @chainable
* @method constant
* @param {string} name The constant name.
* @param {*} value The constant value.
* @return {ima.ObjectContainer} This object container.
*/
constant(name, value) {
if ($Debug) {
if (this._constants.has(name) || !!this._getEntryFromConstant(name)) {
throw new Error(`ima.ObjectContainer:constant The ${name} ` +
`constant has already been declared and cannot be ` +
`redefined.`);
}
}
var constantEntry = this._createEntry(() => value);
constantEntry.sharedInstance = value;
this._constants.set(name, constantEntry);
return this;
}
/**
* Configures the object loader with the specified default dependencies for
* the specified class.
*
* New instances of the class created by this object container will receive
* the provided dependencies into constructor unless custom dependencies
* are provided.
*
* @chainable
* @method inject
* @template T
* @param {function(new: T, ...*)} classConstructor The class constructor.
* @param {*[]} dependencies The dependencies to pass into the
* constructor function.
* @return {ima.ObjectContainer} This object container.
*/
inject(classConstructor, dependencies) {
if ($Debug) {
if (typeof classConstructor !== 'function') {
throw new Error(`ima.ObjectContainer:inject The first ` +
`argument has to be a class constructor function, ` +
`but ${classConstructor} was provided. Fix your ` +
`bind.js file.`);
}
if (this._registry.has(classConstructor) && !this.isLocked()) {
throw new Error(`ima.ObjectContainer:inject The ` +
`${classConstructor.name} has already had its ` +
`default dependencies configured, and the object ` +
`container is currently locked, therefore the ` +
`dependency configuration cannot be override. The ` +
`dependencies of the provided class must be ` +
`overridden from the application's bind.js ` +
`configuration file.`);
}
}
var newEntry = this._createEntry(classConstructor, dependencies);
this._registry.set(classConstructor, newEntry);
return this;
}
/**
* Configures the default implementation of the specified interface to use
* when an implementation provider of the specified interface is requested
* from this object container.
*
* The implementation constructor will obtain the provided default
* dependencies or the dependencies provided to the {@codelink create()}
* method.
*
* @chainable
* @template {Interface}
* @template {Implementation} extends Interface
* @method provide
* @param {function(new: Interface)} interfaceConstructor The constructor
* of the interface representing the service.
* @param {function(new: Implementation, ...*)} implementationConstructor
* The constructor of the class implementing the service interface.
* @param {*[]} [dependencies=[]] The dependencies to pass into the
* constructor function.
* @return {ima.ObjectContainer} This object container.
*/
provide(interfaceConstructor, implementationConstructor,
dependencies = []) {
if ($Debug) {
if (this._providers.has(interfaceConstructor)) {
throw new Error('ima.ObjectContainer:provide The ' +
'implementation of the provided interface ' +
`(${interfaceConstructor.name}) has already been ` +
`configured and cannot be overridden.`);
}
// check that implementation really extends interface
var prototype = implementationConstructor.prototype;
if (!(prototype instanceof interfaceConstructor)) {
throw new Error('ima.ObjectContainer:provide The specified ' +
`class (${implementationConstructor.name}) does not ` +
`implement the ${interfaceConstructor.name} ` +
`interface.`);
}
}
var newEntry = this._createEntry(
implementationConstructor,
dependencies
);
this._providers.set(interfaceConstructor, newEntry);
return this;
}
/**
* Retrieves the shared instance or value of the specified constant, alias,
* class or factory function, interface, or fully qualified namespace path
* (the method checks these in this order in case of a name clash).
*
* The instance or value is created lazily the first time it is requested.
*
* @template T
* @method get
* @param {(string|function(new: T, ...*)|function(...*): T)} name The name
* of the alias, class, interface, or the class, interface or a
* factory function.
* @return {T} The shared instance or value.
*/
get(name) {
var entry = this._getEntry(name);
if (entry.sharedInstance === null) {
entry.sharedInstance = this._createInstanceFromEntry(entry);
}
return entry.sharedInstance;
}
/**
* Returns the class constructor function of the specified class.
*
* @template T
* @method getConstructorOf
* @param {string|function(new: T, ...*)} name The name by which the class
* is registered with this object container.
* @return {function(new: T, ...*)} The constructor function.
*/
getConstructorOf(name) {
var entry = this._getEntry(name);
return entry.classConstructor;
}
/**
* Returns {@code true} if the specified object, class or resource is
* registered with this object container.
*
* @template T
* @method has
* @param {string|function(new: T, ...*)} name The resource name.
* @return {boolean} {@code true} if the specified object, class or
* resource is registered with this object container.
*/
has(name) {
return this._constants.has(name) ||
this._aliases.has(name) ||
this._registry.has(name) ||
this._providers.has(name) ||
!!this._getEntryFromConstant(name) ||
!!this._getEntryFromNamespace(name) ||
!!this._getEntryFromClassConstructor(name);
}
/**
* Creates a new instance of the class or retrieves the value generated by
* the factory function identified by the provided name, class, interface,
* or factory function, passing in the provided dependencies.
*
* The method uses the dependencies specified when the class, interface or
* factory function has been registered with the object container if no
* custom dependencies are provided.
*
* @template T
* @method create
* @param {(string|function(new: T, ...*)|function(...*): T)} name The name
* of the alias, class, interface, or the class, interface or a
* factory function to use.
* @param {*[]} [dependencies=[]] The dependencies to pass into the
* constructor or factory function.
* @return {T} Created instance or generated value.
*/
create(name, dependencies = []) {
var entry = this._getEntry(name);
return this._createInstanceFromEntry(entry, dependencies);
}
/**
* Clears all entries from this object container and resets the locking
* mechanism of this object container.
*
* @chainable
* @method clear
* @return {ima.ObjectContainer} This object container.
*/
clear() {
this._constants.clear();
this._aliases.clear();
this._registry.clear();
this._providers.clear();
this._lockCounter = 0;
return this;
}
/**
* Returns {@code true} if this object container is locked.
*
* When the object container is locked, it is impossible to register new
* aliases using the {@linkcode bind()} method, or override the
* default class dependencies of any already-configured class using the
* {@linkcode inject()} method (classes that were not configured yet may be
* configured using the {@linkcode inject()} method).
*
* This prevents the unpriviledged code (e.g. 3rd party plugins) from
* overriding the default dependency configuration provided by ima, or
* overriding the configuration of a 3rd party plugin by another 3rd party
* plugin.
*
* The application itself has always access to the unlocked object
* container.
*
* @method isLocked
* @return {boolean}
*/
isLocked() {
return !!(this._lockCounter % 2);
}
/**
* Locks the object container, preventing creation of new aliases and
* overriding the default dependencies of already configured classes.
*
* @chainable
* @method lock
* @return {ima.ObjectContainer} This object container.
* @see #isLocked()
*/
lock() {
if (this.isLocked() || (this._lockCounter !== 0)) {
throw new Error(`ima.ObjectContainer:lock The lock() method has ` +
`to be called only by the bootstrap script. Other calls ` +
`are now allowed.`);
}
this._lockCounter++;
return this;
}
/**
* Unlocks the object container, allowing the creation of new aliases and
* overriding the default dependencies of already configured classes again.
*
* @chainable
* @method unlock
* @return {ima.ObjectContainer} This object container.
*/
unlock() {
if (!this.isLocked() || (this._lockCounter !== 1)) {
throw new Error(`ima.ObjectContainer:unlock The unlock() method ` +
`has to be called only by the bootstrap script. Other ` +
`calls are not allowed.`);
}
this._lockCounter++;
return this;
}
/**
* Retrieves the entry for the specified constant, alias, class or factory
* function, interface, or fully qualified namespace path (the method
* checks these in this order in case of a name clash).
*
* The method retrieves an existing entry even if a qualified namespace
* path is provided (if the target class or interface has been configured
* in this object container).
*
* The method throws an {@codelink Error} if no such constant, alias,
* registry, interface implementation is known to this object container and
* the provided identifier is not a valid namespace path specifying an
* existing class, interface or value.
*
* @private
* @template T
* @method _getEntry
* @param {string|function(new: T, ...*)} name Name of a constant or alias,
* factory function, class or interface constructor, or a fully
* qualified namespace path.
* @return {?Entry<T>} The retrieved entry.
* @throws {Error} If no such constant, alias, registry, interface
* implementation is known to this object container.
*/
_getEntry(name) {
var entry = this._constants.get(name) ||
this._aliases.get(name) ||
this._registry.get(name) ||
this._providers.get(name) ||
this._getEntryFromConstant(name) ||
this._getEntryFromNamespace(name) ||
this._getEntryFromClassConstructor(name);
if ($Debug) {
if (!entry) {
throw new Error(`ima.ObjectContainer:_getEntry There is no ` +
`constant, alias, registered class, registered ` +
`interface with configured implementation or ` +
`namespace entry identified as ${name}. ` +
`Check your bind.js file for typos or register ` +
`${name} with the object container.`);
}
}
return entry;
}
/**
* Creates a new entry for the provided class or factory function and the
* provided dependencies.
*
* @private
* @template T
* @method _createEntry
* @param {(function(new: T, ...*)|function(...*): T)} classConstructor The
* class constructor or factory function.
* @param {*[]} [dependencies=[]] The dependencies to pass into the
* constructor or factory function.
* @return {T} Created instance or generated value.
*/
_createEntry(classConstructor, dependencies = []) {
if (dependencies.length === 0 &&
Array.isArray(classConstructor.$dependencies)) {
dependencies = classConstructor.$dependencies;
}
return new Entry(classConstructor, dependencies);
}
/**
* Creates a new instance of the class or retrieves the value generated by
* the factory function represented by the provided entry, passing in the
* provided dependencies.
*
* The method uses the dependencies specified by the entry if no custom
* dependencies are provided.
*
* @private
* @template T
* @method _createInstanceFromEntry
* @param {Entry<T>} entry The entry representing the class that should
* have its instance created or factory faction to use to create a
* value.
* @param {*[]} [dependencies=[]] The dependencies to pass into the
* constructor or factory function.
* @return {T} Created instance or generated value.
*/
_createInstanceFromEntry(entry, dependencies = []) {
if (dependencies.length === 0) {
dependencies = [];
for (var dependency of entry.dependencies) {
if (['function', 'string'].indexOf(typeof dependency) > -1) {
dependencies.push(this.get(dependency));
} else {
dependencies.push(dependency);
}
}
}
var constructor = entry.classConstructor;
return new constructor(...dependencies);
}
/**
* Retrieves the constant value denoted by the provided fully qualified
* composition name.
*
* The method returns the entry for the constant if the constant is registered
* with this object container, otherwise return {@code null}.
*
* Finally, if the constant composition name does not resolve to value,
* the method return {@code null}.
*
* @private
* @method _getEntryFromConstant
* @param {string} compositionName
* @return {?Entry<T>} An entry representing the value at the specified
* composition name in the constants. The method returns {@code null}
* if the specified composition name does not exist in the constants.
*/
_getEntryFromConstant(compositionName) {
if (typeof compositionName === 'string') {
var objectProperties = compositionName.split('.');
var constantValue = this._constants.has(objectProperties[0]) ?
this._constants.get(objectProperties[0]).sharedInstance :
null;
var pathLength = objectProperties.length;
for (var i = 1; (i < pathLength) && constantValue; i++) {
constantValue = constantValue[objectProperties[i]];
}
if (constantValue !== undefined && constantValue !== null) {
var entry = this._createEntry(() => constantValue);
entry.sharedInstance = constantValue;
return entry;
}
}
return null;
}
/**
* Retrieves the class denoted by the provided fully qualified name within
* the application namespace.
*
* The method then checks whether there are dependecies configured for the
* class, no matter whether the class is an implementation class or an
* "interface" class.
*
* The method returns the entry for the class if the class is registered
* with this object container, otherwise an unregistered entry is created
* and returned.
*
* Finally, if the namespace path does not resolve to a class, the method
* return an unregistered entry resolved to the value denoted by the
* namespace path.
*
* Alternatively, if a constructor function is passed in instead of a
* namespace path, the method returns {@code null}.
*
* @private
* @template T
* @method _getEntryFromNamespace
* @param {(string|function(new: T, ...*))} path Namespace path pointing to
* a class or a value in the application namespace, or a constructor
* function.
* @return {?Entry<T>} An entry representing the value or class at the
* specified path in the namespace. The method returns {@code null}
* if the specified path does not exist in the namespace.
*/
_getEntryFromNamespace(path) {
if (typeof path === 'string' && this._namespace.has(path)) {
var namespaceValue = this._namespace.get(path);
if (typeof namespaceValue === 'function') {
if (this._registry.has(namespaceValue)) {
return this._registry.get(namespaceValue);
}
if (this._providers.has(namespaceValue)) {
return this._providers.get(namespaceValue);
}
return this._createEntry(namespaceValue);
} else {
var entry = this._createEntry(() => namespaceValue);
entry.sharedInstance = namespaceValue;
return entry;
}
}
return null;
}
/**
* Retrieves the class denoted by the provided class constructor.
*
* The method then checks whether there are defined {@code $dependecies}
* property for class. Then the class is registered to this object container.
*
* The method returns the entry for the class if the specified class
* does not have defined {@code $dependencies} property return {@code null}.
* @private
* @method _getEntryFromClassConstructor
* @param {function(new: T, ...*)} classConstructor
* @return {?Entry<T>} An entry representing the value at the specified
* classConstructor. The method returns {@code null}
* if the specified classConstructor does not have defined {@code $dependencies}.
*/
_getEntryFromClassConstructor(classConstructor) {
if (typeof classConstructor === 'function' &&
Array.isArray(classConstructor.$dependencies)) {
this.inject(classConstructor, classConstructor.$dependencies);
return this._registry.get(classConstructor);
}
return null;
}
}
ns.ima.ObjectContainer = ObjectContainer;
/**
* Object container entry, representing either a class, interface, constant or
* an alias.
*
* @class Entry
* @namespace ima
* @module ima
* @template T
*/
class Entry {
/**
* Initializes the entry.
*
* @method constructor
* @param {(function(new: T, ...*)|function(...*): T)} classConstructor The
* class constructor or constant value getter.
* @param {*[]} [dependencies=[]] The dependencies to pass into the
* constructor function.
*/
constructor(classConstructor, dependencies) {
/**
* The constructor of the class represented by this entry, or the
* getter of the value of the constant represented by this entry.
*
* @property classConstructor
* @type {(function(new: T, ...*)|function(...*): T)}
*/
this.classConstructor = classConstructor;
/**
* Dependencies of the class constructor of the class represented by
* this entry.
*
* @property dependencies
* @type {*[]}
*/
this.dependencies = dependencies;
/**
* The shared instance of the class represented by this entry.
*
* @property sharedInstance
* @type {T}
*/
this.sharedInstance = null;
}
}