-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTsSerializer.ts
255 lines (235 loc) · 8.02 KB
/
TsSerializer.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import { ReferenceObjectNotFoundError, TypeNotRegisteredError, UndefinedInputError } from './errors';
import { Resolver } from './Resolver';
import { TransportObject } from './TransportObject';
/**
* Hash that holds the references to the serialized or deserialized objects. Used to resolve references.
*/
type SerializationReferences = {
[type: string]: any[];
};
/**
* Referenced object during deserialization. Since the whole type tree needs to be built before the references
* can be resolved, this intermediate object does serve this purpose.
*
* @class ReferencedObject
*/
class ReferencedObject {
/**
* The typename of the reference.
*
* @type {string}
* @memberOf ReferencedObject
*/
public type: string;
/**
* Then index of the referenced object in the type instance array.
*
* @type {number}
* @memberOf ReferencedObject
*/
public index: number;
constructor(referenceInfo: { type: string, index: number }) {
this.type = referenceInfo.type;
this.index = referenceInfo.index;
}
}
/**
* Main element of this library. Is responsible for the serialization and deserialization of the object structure.
* Throw it a list (or single) of objects which types are registered and it creates a json string out of it.
* On the other side, deserialize the whole stream back into instantiated objects.
*
* @export
* @class TsSerializer
*/
export class TsSerializer {
private references: SerializationReferences;
/**
* Instance of the type resolver.
*
* @readonly
* @type {Resolver}
* @memberOf TsSerializer
*/
public get resolver(): Resolver {
return Resolver.instance;
}
/**
* Serializes a registered object or an array of objects. Creates a special formatted string that can be
* transmitted and deserialized on the other side.
*
* @param {*} objectOrArray The object or array of objects that needs to be serialized.
* @returns {string}
*
* @memberOf TsSerializer
*/
public serialize(objectOrArray: any): string {
if (objectOrArray === undefined) {
throw new UndefinedInputError('serialize');
}
this.references = {};
let serialized: any;
if (objectOrArray !== null && objectOrArray.constructor === Array) {
serialized = objectOrArray.filter(o => o !== undefined).map(o => this.serializeObject(o));
} else {
serialized = this.serializeObject(objectOrArray);
}
return JSON.stringify(serialized);
}
/**
* Deserializes a string that was serialized by {@link TsSerializer#serialize()}. Does parse the whole
* string into instantiated objects.
*
* @template T
* @param {string} json Serialized json string.
* @returns {T}
*
* @memberOf TsSerializer
*/
public deserialize<T>(json: string): T {
if (json === undefined) {
throw new UndefinedInputError('deserialize');
}
this.references = {};
const parsed = JSON.parse(json);
let deserialized: any;
if (parsed !== null && parsed.constructor === Array) {
deserialized = parsed.map(o => this.deserializeObject(o));
} else {
deserialized = this.deserializeObject(parsed);
}
this.resolveReferences(deserialized);
return deserialized;
}
/**
* Recursive function that serializes the objects. Returns a structure of the value and the type reference.
* References to already existing objects (like circular references) are also resolved.
*
* @private
* @param {*} obj
* @returns {TransportObject}
*
* @memberOf TsSerializer
*/
private serializeObject(obj: any): TransportObject {
if (obj === null) {
return {
__type: 'null',
__value: null
};
} else if (obj.constructor === Date) {
return {
__type: 'Date',
__value: obj
};
} else if (obj.constructor === Array) {
return {
__type: 'Array',
__value: obj.map(o => this.serializeObject(o))
};
} else if (typeof obj === 'object') {
const type = this.resolver.getTypeByObject(obj),
transformedObj: any = {};
if (!type) {
throw new TypeNotRegisteredError(obj);
}
if (!this.references[type.name]) {
this.references[type.name] = [];
}
const alreadyIndexed = this.references[type.name].find(o => o === obj);
if (alreadyIndexed) {
return {
__type: 'ref',
__value: {
type: type.name,
index: this.references[type.name].indexOf(obj)
}
};
} else {
this.references[type.name].push(obj);
}
for (let property of Object.keys(obj).filter(o => typeof obj[o] !== 'function' && typeof obj[o] !== 'undefined')) {
transformedObj[property] = this.serializeObject(obj[property]);
}
return {
__type: type.name,
__value: transformedObj
};
} else {
return {
__type: obj.constructor.name,
__value: obj
};
}
}
/**
* Recursive deserialize function that resolves the type names to their instantiated types.
* References are resolved at last, since the whole object tree needs to be built first.
*
* @private
* @param {TransportObject} obj
* @returns {*}
*
* @memberOf TsSerializer
*/
private deserializeObject(obj: TransportObject): any {
switch (obj.__type) {
case 'null':
return null;
case 'Date':
return new Date(obj.__value);
case 'Number':
return Number(obj.__value);
case 'String':
return String(obj.__value);
case 'Boolean':
return Boolean(obj.__value);
case 'Array':
return obj.__value.map(o => this.deserializeObject(o));
case 'ref':
return new ReferencedObject(obj.__value);
default:
const type = this.resolver.getType(obj.__type),
transformedObj: any = {};
if (!type) {
throw new TypeNotRegisteredError(obj);
}
for (let property of Object.keys(obj.__value)) {
transformedObj[property] = this.deserializeObject(obj.__value[property]);
}
const createdObj = type.factory ?
type.factory(transformedObj) :
Object.assign(new (type as any).ctor(), transformedObj);
if (!this.references[type.name]) {
this.references[type.name] = [];
}
this.references[type.name].push(createdObj);
return createdObj;
}
}
/**
* Resolves the referenced objects to actual instances as soon as the whole object tree is built. Is only needed
* during deserialization.
*
* @private
* @param {*} obj
* @returns {void}
*
* @memberOf TsSerializer
*/
private resolveReferences(obj: any): void {
if (obj === null) {
return;
}
for (let property of Object.keys(obj)) {
const prop = obj[property];
if (prop instanceof ReferencedObject) {
if (!this.references[prop.type]) {
throw new ReferenceObjectNotFoundError();
}
obj[property] = this.references[prop.type][prop.index];
} else if (typeof prop === 'object') {
this.resolveReferences(prop);
}
}
}
}