I've run into an issue with the serialization of classes that I don't know how to handle.
I create objects from REST or database requests requests like this:
export interface ILockerModel {
id: string
lockerId: string
ownerId: string
modules: IModuleModel[]
}
export class LockerModel implements ILockerModel {
private _id: string
private _lockerId: string
private _ownerId: string
private _modules: ModuleModel[]
constructor(document: ILockerModel) {
this._id = document.id
this._lockerId = document.lockerId
this._ownerId = document.ownerId
this._modules = document.modules.map(m => new ModuleModel(m))
}
// Utility methods
}
I then have multiple utility methods that make it easier to work with the model, adding and removing things from lists and so on.
When I'm done I want to persist the object to a document database or return it in a REST response, so I call JSON.stringify(objectInstance)
. However, this gives me the class but with all properties underscored (_
), not my getter values. This breaks the deserialization in other parts of my application.
Serializing the interface gives me what I want, but I haven't found a straightforward way to go from the class to the interface representation. The issue gets tougher because I deserialize the data in a hierarchy (see the modules mapping in the constructor).
How do you usually solve this issue?