-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserializer.js
73 lines (55 loc) · 1.66 KB
/
serializer.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
import { isFunction, isObjectLike, isArrayLike } from 'lodash-es'
const isObjectOrArrayLike = (value) => isObjectLike(value) || isArrayLike(value)
export default class Serializer {
constructor (items = []) {
this.registry = {}
items.forEach(i => this.register(i))
}
call (prop, target, def) {
if (isObjectOrArrayLike(target) && isFunction(target[prop])) {
return target[prop]()
}
return def
}
isRegistered (value) {
if (!isObjectOrArrayLike(value) || !value.constructor) {
return false
}
const name = value.constructor.name
return name in this.registry && value instanceof this.registry[name]
}
stringify (data) {
return JSON.stringify(data, (key, value) => {
if (!this.isRegistered(value)) {
return value
}
value = this.call('toJSON', value, value)
return {
...value,
__sid_array__: value instanceof Array,
__sid__: value.constructor.name
}
})
}
parse (data) {
return JSON.parse(data, (key, value) => {
value = this.call('fromJSON', value, value)
if (isObjectLike(value) && value.__sid__ && this.registry[value.__sid__]) {
const sid = value.__sid__
const sidArray = value.__sid_array__
delete value['__sid__']
delete value['__sid_array__']
if (sidArray) {
return this.registry[sid].prototype.constructor.from(Object.values(value))
}
const obj = Object.create(this.registry[sid].prototype)
return Object.assign(obj, value)
}
return value
})
}
register (type, name = null) {
name = name || type.name
this.registry[name] = type
}
}