All files / src/classes/decorators ToStringFieldDecorator.ts

87.5% Statements 7/8
83.33% Branches 5/6
100% Functions 2/2
87.5% Lines 7/8

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          1x                             4x                 1x         4x                       4x 3x       4x    
import PrjBaseData from 'src/models/Data/PrjBaseData';
 
/**
 * A unique symbol used to mark properties that should be included in the {@link PrjBaseData.toString} method.
 */
export const ToStringFieldSymbol: unique symbol = Symbol('ToStringField');
 
/**
 * Represents the field configuration properties.
 */
interface IToStringField_ {
    [ToStringFieldSymbol]?: string[];
}
 
/**
 * Type guard to check if an object is an instance of {@link IToStringField_}.
 * @param obj The object to check.
 * @returns Ever `True` because the {@link ToStringFieldSymbol} property is optional.
 */
function isIToStringField_(obj: unknown): obj is IToStringField_ {
    return true;
}
 
/**
 * A decorator function to mark class properties for inclusion in the toString output.
 * @param target The target object (the class prototype).
 * @param propertyKey The key of the property being decorated.
 * @remarks - Create a {@link ToStringFieldSymbol} property in the class to get the field configurations.
 */
export function toStringField(
    target: unknown,
    propertyKey: string | symbol,
): void {
    // Check if the target is an object guard the optional `ToStringFieldSymbol` property.
    Iif (
        !target ||
        typeof target !== 'object' ||
        !(target instanceof Object) ||
        !isIToStringField_(target.constructor)
    ) {
        throw new Error(
            'The toStringField decorator can only be used on class properties.',
        );
    }
 
    // If the class does not have a `ToStringFieldSymbol` property, create it.
    if (!target.constructor[ToStringFieldSymbol]) {
        target.constructor[ToStringFieldSymbol] = [];
    }
 
    // Push the property key to the `ToStringFieldSymbol` property.
    target.constructor[ToStringFieldSymbol].push(propertyKey.toString());
}
 
Zur TypeDoc-Dokumentation