-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdeserialize.js
More file actions
71 lines (54 loc) · 1.87 KB
/
deserialize.js
File metadata and controls
71 lines (54 loc) · 1.87 KB
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
const debug = require('debug')('json-immutable')
const immutable = require('immutable')
function deserialize(json, options = {}) {
return JSON.parse(json, (key, value) => {
return revive(key, value, options)
})
}
function revive(key, value, options) {
if (typeof value === 'object' && value) {
if (value['__record']) {
return reviveRecord(key, value, options)
} else if (value['__iterable']) {
return reviveIterable(key, value, options)
} else if (value['__date']) {
return new Date(value['__date'])
} else if (value['__regexp']) {
const regExpParts = value['__regexp'].split('/')
return new RegExp(regExpParts[1], regExpParts[2])
}
}
return value
}
function reviveRecord(key, recInfo, options) {
const RecordType = options.recordTypes && options.recordTypes[recInfo['__record']]
if (!RecordType) {
if (options.parseUnknownRecords) {
var TmpRecordType = new immutable.Record(recInfo['data']);
return TmpRecordType(revive(key, recInfo['data'], options))
}
throw new Error(`Unknown record type: ${recInfo['__record']}`)
}
return RecordType(revive(key, recInfo['data'], options))
}
function reviveIterable(key, iterInfo, options) {
switch (iterInfo['__iterable']) {
case 'List':
return immutable.List(revive(key, iterInfo['data'], options))
case 'Set':
return immutable.Set(revive(key, iterInfo['data'], options))
case 'OrderedSet':
return immutable.OrderedSet(revive(key, iterInfo['data'], options))
case 'Stack':
return immutable.Stack(revive(key, iterInfo['data'], options))
case 'Map':
return immutable.Map(revive(key, iterInfo['data'], options))
case 'OrderedMap':
return immutable.OrderedMap(revive(key, iterInfo['data'], options))
default:
throw new Error(`Unknown iterable type: ${iterInfo['__iterable']}`)
}
}
module.exports = {
deserialize,
}