Proper decorator-based transformation / serialization / deserialization of plain javascript objects to class constructors
npm install @ukitgroup/class-transformerObject class.
{} notation.
class notation.
JSON.parse it you have a plain javascript object, not instance of class you have.
users.json that you are loading:
json
[{
"id": 1,
"firstName": "Johny",
"lastName": "Cage",
"age": 27
},
{
"id": 2,
"firstName": "Ismoil",
"lastName": "Somoni",
"age": 50
},
{
"id": 3,
"firstName": "Luke",
"lastName": "Dacascos",
"age": 12
}]
`
And you have a User class:
`javascript
export class User {
id: number;
firstName: string;
lastName: string;
age: number;
getName() {
return this.firstName + " " + this.lastName;
}
isAdult() {
return this.age > 36 && this.age < 60;
}
}
`
You are assuming that you are downloading users of type User from users.json file and may want to write
following code:
`javascript
fetch("users.json").then((users: User[]) => {
// you can use users here, and type hinting also will be available to you,
// but users are not actually instances of User class
// this means that you can't use methods of User class
});
`
In this code you can use users[0].id, you can also use users[0].firstName and users[0].lastName.
However you cannot use users[0].getName() or users[0].isAdult() because "users" actually is
array of plain javascript objects, not instances of User object.
You actually lied to compiler when you said that its users: User[].
So what to do? How to make a users array of instances of User objects instead of plain javascript objects?
Solution is to create new instances of User object and manually copy all properties to new objects.
But things may go wrong very fast once you have a more complex object hierarchy.
Alternatives? Yes, you can use class-transformer. Purpose of this library is to help you to map you plain javascript
objects to the instances of classes you have.
This library also great for models exposed in your APIs,
because it provides a great tooling to control what your models are exposing in your API.
Here is example how it will look like:
`javascript
fetch("users.json").then((users: Object[]) => {
const realUsers = plainToClass(User, users);
// now each user in realUsers is instance of User class
});
`
Now you can use users[0].getName() and users[0].isAdult() methods.
Installation
$3
1. Install module:
npm install @ukitgroup/class-transformer --save
2. reflect-metadata shim is required, install it too:
npm install reflect-metadata --save
and make sure to import it in a global place, like app.ts:
`javascript
import "reflect-metadata";
`
3. ES6 features are used, if you are using old version of node.js you may need to install es6-shim:
npm install es6-shim --save
and import it in a global place like app.ts:
`javascript
import "es6-shim";
`
$3
1. Install module:
npm install @ukitgroup/class-transformer --save
2. reflect-metadata shim is required, install it too:
npm install reflect-metadata --save
add