-
Notifications
You must be signed in to change notification settings - Fork 0
/
mappers.js
100 lines (81 loc) · 2.49 KB
/
mappers.js
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
'use strict';
const assert = require('assert');
function id(val) {
return val;
}
const idMapper = {
serialize: id,
deserialize: id,
};
function createCategorizedInstanceMapper(CategorizedClass) {
return {
serialize:
function serializeCategorizedInstance(instance, embeds, isPartial) {
assert(instance instanceof CategorizedClass);
return instance.serialize(embeds, isPartial);
},
deserialize: function deserializeInstance(properties, isPartial) {
const instance = new CategorizedClass();
instance.category = this.category;
return instance.deserialize(properties, isPartial);
}
};
}
function createInstanceMapper(Class) {
return {
serialize: function serializeInstance(instance, embeds, isPartial) {
assert(instance instanceof Class);
return instance.serialize(embeds, isPartial);
},
deserialize: function deserializeInstance(properties, isPartial) {
const instance = new Class();
return instance.deserialize(properties, isPartial);
}
};
};
function createArrayMapper(itemMapper) {
return {
serialize: function serializeArray(array, embeds, isPartial) {
assert(Array.isArray(array));
return array
.map(item => itemMapper.serialize.call(this, item, embeds, isPartial));
},
deserialize: function deserializeArray(array, isPartial) {
return array
.map(item => itemMapper.deserialize.call(this, item, isPartial));
}
};
};
function createPolymorphicMapper(instanceMapper, mapping) {
return {
serialize: function serializePolymorphic(instance, embeds, isPartial) {
const Class = instance.constructor;
const serialized = instanceMapper(Class).
serialize.call(this, instance, embeds, isPartial);
return {
_class: Class.name,
_properties: serialized,
};
},
deserialize:
function deserializePolymorphic({ _class, _properties }, isPartial) {
assert(mapping.has(_class));
const Class = mapping.get(_class);
return instanceMapper(Class).deserialize.call(this, _properties, isPartial);
}
};
};
const mappers = module.exports = {
idMapper,
createInstanceMapper,
createArrayMapper,
createPolymorphicMapper,
createCategorizedInstanceMapper,
};
const dsl = {};
dsl.identical = idMapper;
dsl.instanceOf = createInstanceMapper;
dsl.arrayOf = createArrayMapper;
dsl.polymorphic = createPolymorphicMapper;
dsl.categorized = createCategorizedInstanceMapper;
Object.assign(mappers, dsl);