When localForage persists objects, it first serializes them to JSON. Since we are using TypeScript classes for our data model, one issue that we have to tackle right away is How can we serialize TypeScript class instances to JSON?
There are actually many answers to this question. The most obvious one is to use JSON.stringify (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), a standard API that converts JavaScript objects to a JSON string. However that solution is hard to implement, if you try it out you'll see that private fields will be serialized without taking getters into account. Hence, the JSON objects will have keys such as _name, which is far from ideal.
Other answers include the following:
- Implementing base classes to handle serialization: This is not great and there is a big risk of introducing subtle bugs.
- Implementing a toJSON function on the prototype, which should be called by JSON.stringify: This is far from straightforward, especially for more advanced cases (complex data structures, circular references, and much more); again there is a risk of introducing bugs.
There is also a second closely related issue that we need to solve: How can we deserialize a JSON object back into a class instance?
There are actually even harder problems to consider (for example, how to properly handle versioning), but we'll only focus on those two issues for now.
To ease our lives and reduce the risk of introducing bugs, we will use the class-transformer (https://github.com/typestack/class-transformer) library. This library can handle both the serialization and deserialization of classes from/to POJOs or literal objects.
Using class-transformer, we will add decorators such as @Expose() to our classes in order to guide class-transformer when it performs serialization/deserialization.