-
Notifications
You must be signed in to change notification settings - Fork 8
/
serializer.ts.handlebars
57 lines (48 loc) · 1.52 KB
/
serializer.ts.handlebars
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
{{#if _options.testRun }}
const model = require("./model");
{{else}}
import * as model from "./model";
{{/if}}
// takes a JSON response and deserializes it into the required model objects / types
export function deserialize(json: any, type: string): any {
// handle arrays
if (type.endsWith("[]")) {
const arrayType = type.substring(0, type.length - 2);
return json.map((item: any) => deserialize(item, arrayType));
}
// handle model objects
if (model.models.includes(type)) {
const modelObject = new (<any>model)[type]();
const properties = (<any>model)[type].propertyTypes;
for (const property of properties) {
if (json[property.name] !== undefined) {
modelObject[property.name] = deserialize(json[property.name], property.type);
}
}
return modelObject;
}
// handle date types
if (type === "Date") {
return new Date(json);
}
// handle additional properties
const match = type.match(/\{ \[name: string\]: (.*) \}/);
if (match) {
const typeName = match[1];
const modelObject: { [name: string]: any } = {};
for (const key in json) {
modelObject[key] = deserialize(json[key], typeName);
}
return modelObject;
}
return json;
}
export function serialize(item: any, type: string): string {
if (type.endsWith("[]")) {
const arrayType = type.substring(0, type.length - 2);
return item
.map((item: any) => serialize(item, arrayType))
.join(",");
}
return typeof item === "object" ? JSON.stringify(item) : item.toString();
}