forked from rt2zz/redux-persist-transform-immutable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialize.js
61 lines (56 loc) · 2.57 KB
/
serialize.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
var helpers = require('./helpers');
var jsan = require('jsan');
var Immutable = require('immutable')
var mark = helpers.mark;
var extract = helpers.extract;
var refer = helpers.refer;
function stringify(data, refs) {
return jsan.stringify(data, serialize(Immutable, refs).replacer, null, true);
}
function parse(data, refs) {
return jsan.parse(data, serialize(Immutable, refs).reviver);
}
function serialize(Immutable, refs) {
return {
replacer: function(key, value) {
if (value instanceof Immutable.Record) return refer(value, 'ImmutableRecord', 'toObject', refs);
if (value instanceof Immutable.Range) return extract(value, 'ImmutableRange');
if (value instanceof Immutable.Repeat) return extract(value, 'ImmutableRepeat');
if (Immutable.OrderedMap.isOrderedMap(value)) return mark(value, 'ImmutableOrderedMap', 'toObject');
if (Immutable.Map.isMap(value)) return mark(value, 'ImmutableMap', 'toObject');
if (Immutable.List.isList(value)) return mark(value, 'ImmutableList', 'toArray');
if (Immutable.OrderedSet.isOrderedSet(value)) return mark(value, 'ImmutableOrderedSet', 'toArray');
if (Immutable.Set.isSet(value)) return mark(value, 'ImmutableSet', 'toArray');
if (Immutable.Seq.isSeq(value)) return mark(value, 'ImmutableSeq', 'toArray');
if (Immutable.Stack.isStack(value)) return mark(value, 'ImmutableStack', 'toArray');
return value;
},
reviver: function(key, value) {
if (typeof value === 'object' && value !== null && '__serializedType__' in value) {
var data = value.data;
switch (value.__serializedType__) {
case 'ImmutableMap': return Immutable.Map(data);
case 'ImmutableOrderedMap': return Immutable.OrderedMap(data);
case 'ImmutableList': return Immutable.List(data);
case 'ImmutableRange': return Immutable.Range(data._start, data._end, data._step);
case 'ImmutableRepeat': return Immutable.Repeat(data._value, data.size);
case 'ImmutableSet': return Immutable.Set(data);
case 'ImmutableOrderedSet': return Immutable.OrderedSet(data);
case 'ImmutableSeq': return Immutable.Seq(data);
case 'ImmutableStack': return Immutable.Stack(data);
case 'ImmutableRecord':
return refs && refs[value.__serializedRef__] ? new refs[value.__serializedRef__](data) : Immutable.Map(data);
default: return data;
}
}
return value;
}
}
}
module.exports = function(Immutable, refs) {
return {
stringify: stringify,
parse: parse,
serialize: serialize
}
};