This is a snippet of code from a project I proposed to my team that was going to automate processes relating to serialization and deserialization of objects sent between our clients (web, desktop, ios, android, macos). All of our web and desktop clients were JS based and each of them included an individual implementation for serializing objects received from other clients. I proposed a library to abstract all of that logic away from the clients and also avoid having to modify code in every client when a change was needed.
This piece of code is related to deserialization of objects.
A lot of our objects (models) inherited from BaseModel
and most of these objects made use of data structures or types
that weren't compatible with JSON. If we had an object like this:
const object = {
items: new Set([1, 2, 3, 4, 5]),
date: new Date(),
id: new UUID(), // custom internal class
somNestedObject: {
items: new Set([6, 7, 8, 9])
}
};
This object isn't straighforward to JSON.stringify()
, since JSON is only compatible with objects and general data
types like arrays, numbers, strings and booleans. With the previous code, the stringify()
call evaluates to something like:
"
{
"items": {},
"date": "2023-03-16T22:52:14.111Z",
id: {},
somNestedObject: {
items: {}
}
}
"
As you can see, this is not what we wanted at all. So the code based on this gist is what basically automates this for
any type of object that inherits BaseModel
and it goes through all the the defined properties (with getters)
and transform the type to a compatible one (EG items: new Set([1, 2, 3, 4, 5])
-> items: [1, 2, 3, 4, 5]
). It pretty
much gets it ready for "stringifying".