All files / lib DefinitionRepository.ts

83.33% Statements 20/24
100% Branches 4/4
75% Functions 6/8
82.6% Lines 19/23

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    12x     12x 45x     45x               339x 4x   335x       71x 146x 52x       19x 18x     1x       3x   3x 10x 9x 6x       3x                    
import { IInstantiatable } from "./interfaces/IInstantiatable";
import { IContainerOption } from "./Container";
import { Keys } from "./Keys";
import { Type } from "./interfaces/IType";
 
export class DefinitionRepository {
    definitions = new Map<string, IInstantiatable>();
 
 
    constructor(private readonly options: IContainerOption) {
    }
 
    getDefinitions(): Map<string, IInstantiatable> {
        return this.definitions;
    }
 
    getDefinition(key: string): IInstantiatable {
        if (!this.definitions.has(key)) {
            throw new Error(`${key} instance is undefined`);
        }
        return this.definitions.get(key) as IInstantiatable;
    }
 
    getDefinitionByType(constructor: Type): IInstantiatable | symbol {
        for (const [key, value] of this.definitions.entries()) {
            if (value.definition.content === constructor) {
                return value;
            }
        }
 
        if (this.options.enableAutoCreate) {
            return Keys.AUTO_CREATE_DEPENDENCY;
        }
 
        throw new Error(`Definition not found by type: ${constructor}`);
    }
 
    getDefinitionKeysBySpecificTags(tags: string[]): string[] {
        const resultKeys: string[] = [];
 
        this.definitions.forEach((value: IInstantiatable, key: string) => {
            const foundTag = tags.find(tag => value.tags.includes(tag));
            if (foundTag) {
                resultKeys.push(key);
            }
        });
 
        return resultKeys;
    }
 
    addTags(key: string, tags: string[]): string[] {
        const definition = this.getDefinition(key);
        definition.tags.push(...tags);
        return definition.tags;
    }
 
}