diff --git a/changelog.md b/changelog.md index 71e55ee..184228a 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,12 @@ # Changelog +## 2025-04-24 - 5.15.0 - feat(svDb) +Enhance svDb decorator to support custom serialization and deserialization options + +- Added an optional options parameter to the svDb decorator to accept serialize/deserialize functions +- Updated instance creation logic (updateFromDb) to apply custom deserialization if provided +- Updated createSavableObject to use custom serialization when available + ## 2025-04-23 - 5.14.1 - fix(db operations) Update transaction API to consistently pass optional session parameters across database operations diff --git a/ts/00_commitinfo_data.ts b/ts/00_commitinfo_data.ts index 653646c..6ab90b2 100644 --- a/ts/00_commitinfo_data.ts +++ b/ts/00_commitinfo_data.ts @@ -3,6 +3,6 @@ */ export const commitinfo = { name: '@push.rocks/smartdata', - version: '5.14.1', + version: '5.15.0', description: 'An advanced library for NoSQL data organization and manipulation using TypeScript with support for MongoDB, data validation, collections, and custom data types.' } diff --git a/ts/classes.doc.ts b/ts/classes.doc.ts index 2254063..37d000c 100644 --- a/ts/classes.doc.ts +++ b/ts/classes.doc.ts @@ -39,16 +39,34 @@ export function globalSvDb() { }; } +/** + * Options for custom serialization/deserialization of a field. + */ +export interface SvDbOptions { + /** Function to serialize the field value before saving to DB */ + serialize?: (value: any) => any; + /** Function to deserialize the field value after reading from DB */ + deserialize?: (value: any) => any; +} + /** * saveable - saveable decorator to be used on class properties */ -export function svDb() { +export function svDb(options?: SvDbOptions) { return (target: SmartDataDbDoc, key: string) => { console.log(`called svDb() on >${target.constructor.name}.${key}<`); if (!target.saveableProperties) { target.saveableProperties = []; } target.saveableProperties.push(key); + // attach custom serializer/deserializer options to the class constructor + const ctor = target.constructor as any; + if (!ctor._svDbOptions) { + ctor._svDbOptions = {}; + } + if (options) { + ctor._svDbOptions[key] = options; + } }; } @@ -189,7 +207,12 @@ export class SmartDataDbDoc { const saveableObject: unknown = {}; // is not exposed to outside, so any is ok here const saveableProperties = [...this.globalSaveableProperties, ...this.saveableProperties]; + // apply custom serialization if configured + const optionsMap = (this.constructor as any)._svDbOptions || {}; for (const propertyNameString of saveableProperties) { - saveableObject[propertyNameString] = this[propertyNameString]; + const rawValue = (this as any)[propertyNameString]; + const opts = optionsMap[propertyNameString]; + (saveableObject as any)[propertyNameString] = opts && typeof opts.serialize === 'function' + ? opts.serialize(rawValue) + : rawValue; } return saveableObject as TImplements; }