-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample2.ts
100 lines (82 loc) · 2.07 KB
/
example2.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import {Serializable, Deserialize, Deserializable, Serializer, Deserializer, Serialize} from '../lib/index';
import {inspect} from "util";
@Serializable()
@Deserializable()
class Person {
@Deserialize()
private _name: string;
@Deserialize()
private _posts: Post[];
constructor(name: string) {
this._name = name;
this._posts = [];
}
@Serialize()
get name(): string {
return this._name;
}
@Serialize()
get posts(): Post[] {
return this._posts;
}
@Serialize()
get postsCount() {
return this.posts.length;
}
public sayHello(){
return `Hello, my name is ${this.name}`;
}
}
@Serializable()
@Deserializable()
class Post {
@Deserialize()
private _title: string;
@Deserialize()
private _author: Person;
constructor(title: string, author: Person) {
this._title = title;
this._author = author;
}
@Serialize()
get title(): string {
return this._title;
}
@Serialize()
get author(): Person {
return this._author;
}
}
const separatorString = Array(50).fill('#').join('');
const martin = new Person('Martin');
martin.posts.push(...[
new Post('First post', martin),
new Post('Second post', martin)]
);
console.log(martin);
console.log(martin.sayHello());
console.log(separatorString);
const serializer = new Serializer(martin, {operationMode:'both'});
const martinJSON = serializer.serialize();
console.log(inspect(martinJSON, {depth: 5}));
console.log(separatorString);
const deserializer = new Deserializer(martinJSON);
deserializer.constructorProvider = (className: string) => {
const NullClass = function () {
};
NullClass.prototype = null;
switch (className) {
case null:
return NullClass;
case 'Person':
return Person;
case 'Post':
return Post;
case 'Object':
default:
return Object;
}
};
const martin2 = <Person> deserializer.deserialize();
console.log(martin2);
console.log(martin2.sayHello());