Created
April 14, 2020 11:23
-
-
Save andriyor/d60dd936f9334910c8ec4b6fd8e3b7bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "es6-shim"; | |
import "reflect-metadata"; | |
import {deserializeArray, Expose, plainToClass, Transform, Type} from "class-transformer"; | |
export function Default(defaultValue: any) { | |
return Transform((value: any) => (value !== null && value !== undefined ? value : defaultValue)); | |
} | |
export class Pet { | |
name: string; | |
} | |
export class Petc { | |
name: string; | |
constructor(data: Pet) { | |
this.name = data.name; | |
} | |
} | |
export class User { | |
id: number; | |
firstName: string; | |
lastName: string; | |
age: number; | |
@Expose() | |
@Default([]) | |
@Type(() => Pet) | |
pets: Pet[]; | |
} | |
export class Userc { | |
id: number; | |
firstName: string; | |
lastName: string; | |
age: number; | |
pets?: Pet[]; | |
constructor(data: Userc) { | |
this.id = data.id; | |
this.firstName = data.firstName; | |
this.lastName = data.lastName; | |
this.age = data.age; | |
this.pets = data?.pets?.map(pet => new Petc(pet)) || []; | |
} | |
} | |
const userJson = [{ | |
"id": 1, | |
"firstName": "Johny", | |
"lastName": "Cage", | |
"age": 27, | |
"unkownProp": 'hello there', | |
"pets": [{"name": "Miky"}] | |
}, | |
{ | |
"id": 2, | |
"firstName": "Ismoil", | |
"lastName": "Somoni", | |
"age": 50, | |
}, | |
{ | |
"id": 3, | |
"firstName": "Luke", | |
"lastName": "Dacascos", | |
"age": 12, | |
"pets": [{"name": "Miky"}] | |
}] | |
let users = deserializeArray(User, JSON.stringify(userJson)); | |
const usersc = userJson.map(user => new Userc(user)); | |
console.log(userJson[0] instanceof User) | |
console.log(userJson[0] instanceof Object) | |
console.log() | |
console.log(users[0] instanceof User) | |
console.log(users[0] instanceof Userc) | |
console.log(users[0] instanceof Object) | |
users[0].pets.push(plainToClass(Pet, {"name": "Tom"})) | |
console.log() | |
console.log(usersc[0] instanceof User) | |
console.log(usersc[0] instanceof Userc) | |
console.log(usersc[0] instanceof Object) | |
usersc[0].pets.push(new Petc({"name": "Tom"})) | |
console.log() | |
console.log(users); | |
console.log() | |
console.log(usersc); | |
console.log(users[0].pets[0] instanceof Pet) | |
console.log(usersc[0].pets[0] instanceof Petc) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment