All files / src/PerfectWSAdvanced/transform CustomTransformers.ts

100% Statements 34/34
100% Branches 12/12
100% Functions 5/5
100% Lines 34/34

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 462x 2x   2x         2x   2x 2x 1294x   2x 2911x 38x 38x 1x 1x   37x 2911x 2911x   2x 2996x 2996x 2996x 2996x 2996x   2x 14765x 14765x 41x 41x 41x 41x 41x 41x   14724x 14765x 2x  
import { transformSendDeserializeType, transformSendRecursive } from './utils/changeType.js';
import { PerfectWSError } from '../../PerfectWSError.js';
 
export abstract class TransformInstruction<T> {
    abstract check(data: any): data is T;
    abstract uniqueId: string;
    abstract serialize(data: T): any;
    abstract deserialize(data: string): T;
};
 
export class CustomTransformers {
    constructor(private _transformers: TransformInstruction<any>[], private _maxDepth: number = 100) {
    }
 
    deserialize(data: any) {
        return transformSendDeserializeType(data, 'customTransformer', found => {
            const instance = this._transformers.find(c => c.uniqueId === found.uniqueId);
            if (!instance) {
                throw new PerfectWSError(`Transform instruction not found: ${found.uniqueId}`);
            }
 
            return instance.deserialize(found.serialized);
        }, this._maxDepth);
    }
 
    serialize(obj: any) {
        return transformSendRecursive(obj, {
            maxDepth: this._maxDepth,
            transformData: (data) => this._serializeClassInstance(data)
        });
    }
    
    private _serializeClassInstance(instance: any) {
        const foundTransform = this._transformers.find(x => x.check(instance));
        if (foundTransform) {
            return {
                ___type: 'customTransformer',
                serialized: foundTransform.serialize(instance),
                uniqueId: foundTransform.uniqueId
            };
        }
 
        return null
    }
}