Handling serialization/deserialization

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:

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.

Decorators are a fairly advanced feature of TypeScript, somewhat akin to attributes in C# and annotations in Java. We'll cover decorators in greater detail when we implement our first Angular application together. For now, just know that they are actually functions that can be used to add metadata and/or processing to different kinds of element. Decorators still exist at runtime. As we saw earlier, decorator support is enabled through the experimentalDecorators flag in tsconfig.json.