All files / lib/decorators Inject.ts

100% Statements 14/14
94.11% Branches 16/17
100% Functions 2/2
100% Lines 14/14

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 385x 5x           5x 30x         30x 30x   30x   30x 30x 22x 22x     30x     30x 30x                  
import "reflect-metadata";
import { Keys } from "../Keys";
import { Type } from "../interfaces/IType";
 
/*
* Save meta for constructor parameter or function parameter
* */
export function Inject<T = any>(propertyKey?: string | Type<T>) {
    return (
        target: any,
        key: string | symbol,
        parameterIndex: number
    ) => {
        const ctrOrTarget = key ? target.constructor : target;
        const metaKey = key ? key : Keys.INJECT_PROPERTY_DECORATOR_KEY;
 
        const reqParamCount = target[key]?.length || target?.length;
 
        const metadata: any = Reflect.getMetadata(metaKey, ctrOrTarget) || {};
        if (metadata[metaKey] === undefined) {
            metadata[metaKey] = [];
            metadata[Keys.IS_REQUIRED_PARAM] = [];
        }
 
        const param: IInjectParamMeta = {key: propertyKey, isRequired: (parameterIndex < reqParamCount), index: parameterIndex};
 
        // @ts-ignore
        metadata[metaKey][parameterIndex] = param;
        Reflect.defineMetadata(metaKey, metadata, ctrOrTarget);
    };
}
 
export interface IInjectParamMeta {
    key: any;
    isRequired: boolean;
    index: number;
}