objectsm
v2.0.2
Published
JS Object Serializer/Deserializer Manager to convert JS objects with saved metadata back into instances of the class they were created with. This library intends to behave like PHP serialize/deserialize does.
Downloads
29
Maintainers
Readme
JS Object Serialization Manager
JS Object Serializer/Deserializer Manager to convert JS objects with saved metadata back into instances of the class they were created with. This library intends to behave like PHP serialize/deserialize does.
This library lets you define models as JavaScript classes, complete with methods/defaults and ability to post process the data.
This library will recursively iterate a JS object and automatically replace all references with their original class form, letting you deserialize back into the original objects that actually created it.
Install
npm install objectsm
Usage
import ObjectManager, {ObjectBase} from "objectsm";
class Test2 extends ObjectBase {
baz: string;
}
class Test4 extends ObjectBase {
hello: string;
}
class Test3 extends ObjectBase {
qux: number;
test4: Test4;
}
class Test1 extends ObjectBase {
foo: Test2;
bar: Test3;
}
const testManager = new ObjectManager({
mappings: {
"test1": Test1,
"test2": Test2,
"test3": Test3,
"test4": Test4,
}
});
async function test() {
const obj = await testManager.deserializeObject({
":cls": "test1",
"foo": {
":cls": "test2",
"baz": "Hello"
},
"bar": {
":cls": "test3",
"qux": 42,
"test4": {
":cls": "test4",
"hello": "world!"
}
}
});
console.log(obj.bar.test4 instanceof Test4); // true
}
ObjectBase is optional, but it will expose .rawData()
and allow lazy deserializing with .deserializeObject()