All files / lib/modifiers/initializers RunBeforeModifier.ts

92.85% Statements 13/14
63.63% Branches 7/11
100% Functions 4/4
100% Lines 13/13

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 3212x         12x 45x         59x       59x 59x   59x 1x 1x 1x 1x 1x       59x        
import { Keys } from "../../Keys";
import { IRunBefore } from "../../interfaces/IRunBefore";
import { IResolver } from "../../interfaces/IResolver";
import { IInitializer } from "./IInitializer";
 
export class RunBeforeModifier implements IInitializer {
    constructor(readonly resolver: IResolver) {
 
    }
 
    async run(instance: any, definition: any): Promise<any> {
        return this.setBeforeMethod(instance, definition);
    }
 
    async setBeforeMethod(resolvedInstance: any, definition: any): Promise<any> {
        const beforeMeta = Reflect.getMetadata(Keys.BEFORE_METHOD_KEY, resolvedInstance.constructor) || {};
        Iif (!beforeMeta) return resolvedInstance;
 
        for (const key in beforeMeta) {
            const resolveRunBefore: IRunBefore = typeof beforeMeta[key] === "string" ? await this.resolver.resolve(beforeMeta[key]) : await this.resolver.resolveByType(beforeMeta[key]);
            const descriptorOriginal = Reflect.getMetadata(Keys.METHOD_DESCRIPTOR_KEY, resolvedInstance.constructor) || {};
            resolvedInstance[key]  =  function (this: any, ...args: any) {
                resolveRunBefore.run();
                return descriptorOriginal.value?.apply(this, args);
            };
        }
 
        return resolvedInstance;
    }
 
}