-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
86 lines (67 loc) · 1.96 KB
/
index.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
import {Description} from './lib/description';
import Promise = require('bluebird');
import glob = require('glob');
import _ = require('lodash');
var objectRegistry: { [name: string]: Description } = {};
export function loadPath(path: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
glob(path, function(err: any, files: string[]) {
files.forEach((file) => {
try {
require(file.substr(0, file.length - 3));
} catch(e) {
reject(e);
}
});
resolve();
});
});
}
export function describe(name: string, block: (dsc: Description) => void) {
var description = new Description();
block.call(this, description);
objectRegistry[name] = description;
}
export function serialize(name: string, data: any) {
var description = objectRegistry[name];
var serialized: any = {};
if (description._allow_all) {
serialized = data;
} else {
for (var key of description._allowed_keys) {
serialized[key.as || key.key] = data[key.key];
}
}
for (var refKey in description._references) {
if (!description._references.hasOwnProperty(refKey)) {
return;
}
var ref = description._references[refKey];
if (data[refKey]) {
serialized[ref.as || refKey] = view(ref.descriptionName, data[refKey]);
} else {
delete serialized[refKey];
}
}
description._transformations.forEach((ref) => {
serialized[ref.as || refKey] = ref.transformer(data);
});
if (description._disallowed_keys) {
for (var disallowedKey of description._disallowed_keys) {
delete serialized[disallowedKey];
}
}
return serialized;
}
export function view(name: string, data: any) {
if (!objectRegistry[name]) {
throw new Error('Cannot view object, unknown object: ' + name);
}
var data = _.cloneDeep(data);
if (_.isArray(data)) {
data = data.map((d) => serialize(name, d));
} else {
data = serialize(name, data);
}
return data;
}