All files / lib/modifiers/initializers MethodWrapperModifier.ts

57.14% Statements 8/14
18.18% Branches 2/11
60% Functions 3/5
66.66% Lines 8/12

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