This document shows how to serialize class instances into plain objects and, conversely, how to deserialize plain objects into class instances. It is based on the class-transformer library.
Serialization is particularly interesting if you need to transform HTTP request bodies into model instances or, inversely, convert model instances into plain objects to be returned in HTTP responses.
class-transformer has two main functions to transform objects:
classToPlain. Some examples of their use are given below.
Other functions also exist and can be found in the README of the library repository.
Additional options can be provided to the
class-transformer also offers other interesting features (nested objects, property renaming, etc) that can be found here.
Caution: These functions do not validate data. They do not guarantee that all declared properties are assigned and that no additional properties are assigned to the object. They behave more or less like a call to
Object.assign. Please refer to the validation page if you need to validate data.
If you want to use
class-transformer within a hook to transform request bodies, you can install the package
@foal/typestack for this. It provides a
@UnserializeBody hook that transforms the request body into an instance of a given class.
The hook takes also an optional parameter to specify the options of the class-transformer library.