All files / mframejs/container containerClasses.ts

81.25% Statements 13/16
100% Branches 2/2
66.67% Functions 4/6
81.25% Lines 13/16

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 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    29x     29x     29x             29x                   524x   524x                                                 439x       59x     85x                       498x 498x                 498x                                         364x        
 
// dependencies for a class
const dep = new Map();
 
// sigelton classes
const singelton = new Map();
 
// transient classes
const transient = new Map();
 
 
/**
 * keeps track of our classes and dependencies
 *
 */
export class ContainerClasses {
 
 
 
    /**
     * returns a instance of a class, pass in the class type/prototype to get it
     *
     */
    public static get(_class: any): any {
 
        const instance = this.getInstance(_class);
 
        return instance;
 
    }
 
 
 
    /**
     * returns dependencies only (I dont use this atm)
     *
     */
 /*     public static getDepOnly<T>(_class: T): T {
 
        return dep.get(_class);
 
    }
 */
 
 
    /**
     * get instance of class and create if it is not created before
     *
     */
    private static getInstance<T>(_class: T): T {
 
        if (transient.has(_class)) {
            return this.create(_class);
        } else {
 
            if (!singelton.get(_class)) {
                singelton.set(_class, this.create(_class));
            }
 
            return singelton.get(_class);
 
        }
    }
 
 
    /**
     * ...todo
     *
     */
    private static create(_class: any): any {
 
        let deps = dep.get(_class) || [];
        deps = deps.map((classX: any) => {
            try {
                return this.get(classX);
            } catch (e) {
                return classX;
            }
        });
        // @ts-ignore: Unreachable code error
 
        return new _class(...deps);
    }
 
 
 
    /**
     * set dependencies for a class
     *
     */
    public static setDep(_class: any, deps: any) {
        dep.set(_class, deps);
    }
 
 
 
    /**
     * registers a class as transient
     *
     */
    public static regTransient(_class: any) {
        if (!transient.has(_class)) {
            transient.set(_class, null);
        }
    }
}