All files / lib Container.ts

91.76% Statements 78/85
70.96% Branches 22/31
94.44% Functions 17/18
92.77% Lines 77/83

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 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 21612x   12x     12x 12x   12x 12x 12x 12x 12x         12x 12x                       12x   45x 45x 45x   45x   45x   45x         45x 45x             110x 110x 110x 110x 110x                 22x 31x     31x 31x 31x                 44x 43x 43x 18x 18x 18x 25x 25x 25x 25x                     90x   88x 88x   1x 1x     87x                 99x 98x       3x 3x   3x 3x 6x     3x       1x               3x 8x 8x   1x                 1x 1x       1x 1x         37x       110x         110x 63x           63x 63x   47x               1x       87x 74x 73x   73x 73x   13x                  
import "reflect-metadata";
import { IContainer } from "./interfaces/IContainer";
import { InstantiationModeCO } from "./chainingOptions/InstantiationModeCO";
import { IInstantiatable, IInstantiationMode } from "./interfaces/IInstantiatable";
import { IResolver } from "./interfaces/IResolver";
import { ConstructorInstantiation } from "./definitions/ConstructorInstantiation";
import { ConstantInstantiation } from "./definitions/ConstantInstantiation";
import { IInterceptor } from "./interfaces/IInterceptor";
import { Initializers } from "./modifiers/Initializers";
import { Utils } from "./Utils";
import { DefinitionRepository } from "./DefinitionRepository";
import { Keys } from "./Keys";
import { v4 as uuidv4 } from "uuid";
import { Type } from "./interfaces/IType";
import { IInitializer } from "./modifiers/initializers/IInitializer";
import { IBaseDefinition } from "./definitions/definitionInterfaces/IBaseDefinition";
import { IInjectableOptions } from "./decorators/Injectable";
import { isObject, isPrimitive } from "util";
import { Logger } from "./Logger";
 
export type singletonsType = Map<string, any>;
export type logLevelType = "none" | "debug";
 
export interface IContainerOption {
    enableAutoCreate: boolean; // if dependency not exist in the container, creat it and register
    initializers?: Type<IInitializer>[];
    logLevel?: logLevelType;
}
 
 
export class Container implements IContainer, IResolver {
    private logger: Logger;
    definitionsRepository = new DefinitionRepository(this.options);
    protected singletons: singletonsType = new Map<string, any>();
    interceptors: IInterceptor[] = [];
 
    initializers = new Initializers(this);
 
    protected DEFAULT_INSTANTIATION: IInstantiationMode = "singleton";
 
    constructor(public readonly options: IContainerOption = {
        enableAutoCreate: false,
        initializers: [],
        logLevel: "none"
    }) {
        this.initializers.addInitializers(options.initializers || []);
        this.logger = new Logger(Container.name, options.logLevel || "none");
    }
 
    /**
     * Key-Value registration. You can inject the registered keys with @Inject(key) decorator
     */
    public register(key: string, value: any): InstantiationModeCO {
        const decoratorTags = Utils.getMeta<string[]>(Keys.ADD_TAGS_KEY, value, []);
        const injectableMeta = Utils.getMeta<IInjectableOptions>(Keys.INJECTABLE_KEY, value, {instantiation: this.DEFAULT_INSTANTIATION});
        this.logger.debug(`Register:  key: ${key} --> value: ${isPrimitive(value) || isObject(value) ? JSON.stringify(value, null, 2) : Utils.logClass(value)}`);
        this.setDefinition(key, this.getDefaultInstantiationDef(key, value, decoratorTags, injectableMeta.instantiation));
        return new InstantiationModeCO(this, key);
    }
 
    /**
     * Types registration to the container with a random key
     * (type injection don't need keys but if {autoCreate: false} you need to register everything)
     * @param constructors
     */
    public registerTypes(constructors: Type[]): void {
        for (const constructor of constructors) {
            Iif (constructor.name === "String" || constructor.name === "Number") {
                throw new Error(`Can't register primitive as type. Please register another way: ${constructor.name}`);
            }
            const id = uuidv4();
            this.logger.debug(`registerType: ${Utils.logClass(constructor)} key: ${id}`);
            this.register(uuidv4(), constructor);
        }
    }
 
    /**
     * Resolve type
     * @param constructor resolvable ctr
     */
    public async resolveByType<T>(constructor: Type<T>): Promise<T> {
        const def = this.definitionsRepository.getDefinitionByType(constructor);
        this.logger.debug("Try to resolve: " + Utils.logClass(constructor));
        if (def === Keys.AUTO_CREATE_DEPENDENCY && this.options.enableAutoCreate) {
            this.logger.debug("AUTO_CREATE_DEPENDENCY: " + Utils.logClass(constructor));
            this.registerTypes([constructor]);
            return this.resolveByType(constructor);
        } else if (def) {
            const instantiatable = (this.definitionsRepository.getDefinitionByType(constructor) as IInstantiatable);
            const instance = instantiatable.instantiate();
            return this.applyModificationToInstance(instance, instantiatable.definition);
        } else E{
            throw new Error(`cannot resolve ${constructor}`);
        }
    }
 
    /**
     * Resolve key
     * @param key registered key (by register(key: string, value: any))
     */
    public async resolve<T>(key: string): Promise<T> {
        const instantiatable: IInstantiatable = this.definitionsRepository.getDefinition(key);
 
        this.logger.debug(`Try to resolve key: "${key}" as ${instantiatable.definition.instantiationMode}`);
        switch (instantiatable.definition.instantiationMode) {
            case "prototype": {
                const originalInstance = await this.resolvePrototype<T>(instantiatable.definition.key);
                return this.applyModificationToInstance(originalInstance, instantiatable.definition);
            }
            case "singleton": {
                return this.resolveSingleton<T>(instantiatable);
            }
            default: {
                throw new Error(`Cannot resolve: ${key} because instantiationMode is:  ${instantiatable.definition.instantiationMode}`);
            }
        }
    }
 
    async applyModificationToInstance(instance: any, definition: IBaseDefinition) {
        instance = await this.initializers.runInitializers(instance, definition);
        return instance;
    }
 
    async resolveByTags(tags: string | string[]): Promise<any[]> {
        if (typeof tags === "string") { tags = [tags]; }
        const keys = this.definitionsRepository.getDefinitionKeysBySpecificTags(tags);
 
        const result = [];
        for (const key of keys) {
            result.push(await this.resolve(key));
        }
 
        return result;
    }
 
    addInterceptor(interceptor: IInterceptor): void {
        this.interceptors.push(interceptor);
    }
 
 
    /**
     * resolve test for all keys.
     */
    async containerTest() {
        for (const key of this.definitionsRepository.definitions.keys()) {
            try {
                await this.resolve<any>(key);
            } catch (err) {
                throw new Error(`Not proper registration. details: ${err}`);
            }
        }
    }
 
    /**
     * run interceptors. Run this after all key was registered.
     */
    async done(): Promise<any> {
        await this.containerTest();
        this.runInterceptors();
    }
 
    private runInterceptors() {
        this.interceptors.forEach((interceptor: IInterceptor) => {
            interceptor.intercept(this);
        });
    }
 
    hasKeyInDefinition(key: string): boolean {
        return this.definitionsRepository.definitions.has(key);
    }
 
    private setDefinition(key: string, definition: IInstantiatable) {
        this.definitionsRepository.definitions.set(key, definition);
    }
 
    private getDefaultInstantiationDef(key: string, content: any, decoratorTags: string[], instantiationMode?: IInstantiationMode): IInstantiatable {
 
        if (Utils.isClass(content)) {
            const classInstance = new ConstructorInstantiation({
                key,
                content,
                context: {},
                instantiationMode: instantiationMode || this.DEFAULT_INSTANTIATION,
            }, this);
            classInstance.tags = [...decoratorTags];
            return classInstance;
        }
        return new ConstantInstantiation({
            key,
            content,
            instantiationMode: this.DEFAULT_INSTANTIATION
        });
    }
 
    private async resolvePrototype<T>(key: string): Promise<T> {
        return this.definitionsRepository.getDefinition(key).instantiate();
    }
 
    private async resolveSingleton<T>(instantiatable: IInstantiatable): Promise<T> {
        if (!this.singletons.has(instantiatable.definition.key)) {
            let newInstance = await instantiatable.instantiate();
            newInstance = this.applyModificationToInstance(newInstance, instantiatable.definition);
 
            this.singletons.set(instantiatable.definition.key, newInstance);
            return this.singletons.get(instantiatable.definition.key);
        }
        return this.singletons.get(instantiatable.definition.key);
    }
 
    private getTagsMeta(ctr: Type) {
        Iif (!Utils.isClass(ctr)) return;
        const meta = Reflect.getMetadata(Keys.ADD_TAGS_KEY, ctr.prototype) || {};
        return meta[Keys.ADD_TAGS_KEY] || [];
    }
}