UNPKG

@eklabdev/blingts4

Version:

A comprehensive TypeScript decorators library implementing Stage 2 decorators for TS 4.9+

36 lines (35 loc) 1.32 kB
/** * Adds serialization capabilities to a class * @param options Serialization options */ export function Serializable(options = {}) { return function (target) { const { toJSON = true, toObject = true, transform } = options; // Return a class that extends the original class return class SerializableClass extends target { constructor(...args) { super(...args); // Add toJSON method if enabled if (toJSON) { this['toJSON'] = function () { const obj = Object.getOwnPropertyNames(this).reduce((acc, key) => { const value = this[key]; if (typeof value === 'function') { return acc; } acc[key] = transform ? transform(value) : value; return acc; }, {}); return obj; }; } // Add toObject method if enabled if (toObject) { this['toObject'] = function () { return this['toJSON'](); }; } } }; }; }