All files / src/loader loader.ts

100% Statements 22/22
100% Branches 3/3
100% Functions 6/6
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            24x 24x   24x         85x 85x       86x       1x 1x 1x       127x 127x   7x 7x   120x   83x 83x   120x       87x 78x   77x                     24x 1x    
import { IDictionary, INewable } from '../utils/interfaces';
import { IControllerBuilder } from './interfaces';
 
/**
 * Loader
 */
export class Loader {
	private static controllers: IDictionary<INewable<any>> = {};
 
	private static instances: IDictionary = {};
 
	private static builder: IControllerBuilder;
 
	public static setControllers(controllers: IDictionary<INewable<any>>) {
		Loader.controllers = controllers;
		Loader.clearInstances();
	}
 
	public static setBuilder(builder: IControllerBuilder) {
		Loader.builder = builder;
	}
 
	public static addController(name: string, controller: INewable, params?: any[]) {
		Loader.controllers[name] = controller;
		const instance = Loader.builder.build(controller, params);
		Loader.instances[name] = instance;
	}
 
	public static getInstance(name: string) {
		const controller = Loader.controllers[name];
		if (!controller) {
			/* eslint no-console: ["error", { allow: ["error"] }] */
			console.error(`Controller ${name} not found`);
			return null;
		}
		if (!Loader.instances[name]) {
			// Cannot use constructor starting with capital letter because it is a variable
			const instance = Loader.builder.build(controller);
			Loader.instances[name] = instance; // eslint-disable-line new-cap
		}
		return Loader.instances[name];
	}
 
	public static clearInstances() {
		for (const key in Loader.instances) {
			if (!Loader.instances[key]._singleton) {
				// eslint-disable-line no-underscore-dangle
				delete Loader.instances[key];
			}
		}
	}
}
 
/**
 * Singleton decorator
 * When creating a controller using this decorator the controller is not cleared by Loader class
 * @param constructorFunction constructor
 */
export function Singleton(constructorFunction: new (...args: any[]) => any) {
	constructorFunction.prototype._singleton = true; // eslint-disable-line no-underscore-dangle
}