Created
March 27, 2015 16:08
-
-
Save gilbox/a7ff39cb75796c4413cb to your computer and use it in GitHub Desktop.
Use transit-js with Immutable.js and plain JS Objects mixed in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Transit = require('transit-js'), | |
Imm = require('immutable'); | |
// gil: It's possible that the following reader/writer configuration is incomplete. | |
// This is a modified version of: | |
// https://gist.github.com/Tvaroh/52efbe8f4541ca537908 | |
var reader = Transit.reader('json', { | |
mapBuilder: { | |
init: function () { return {}; }, | |
add: function (ret, key, val) { | |
ret[key] = val; | |
return ret; | |
}, | |
finalize: function (ret) { return ret; } | |
}, | |
handlers: { | |
iL: function (arr) { | |
return Imm.List(arr); | |
}, | |
iS: function (arr) { | |
return Imm.Set(arr); | |
}, | |
iM: function (o) { | |
return Imm.Map(o); | |
}, | |
iOM: function (arr) { | |
return Imm.OrderedMap(arr); | |
} | |
} | |
}); | |
var writer = Transit.writer("json-verbose", { | |
handlers: Transit.map([ | |
Imm.List, Transit.makeWriteHandler({ | |
tag: function () { return 'iL'; }, | |
rep: function (v) { return v.toArray(); }, | |
stringRep: function () { return null; } | |
}), | |
Imm.Map, Transit.makeWriteHandler({ | |
tag: function () { return 'iM'; }, | |
rep: function (v) { return v.toObject(); }, | |
stringRep: function () { return null; } | |
}), | |
Imm.Set, Transit.makeWriteHandler({ | |
tag: function () { return 'iS'; }, | |
rep: function (v) { return v.toArray(); }, | |
stringRep: function () { return null; } | |
}), | |
Imm.OrderedMap, Transit.makeWriteHandler({ | |
tag: function () { return 'iOM'; }, | |
rep: function (v) { return v.map(function(v,k) { return [k,v] } ).toArray() }, | |
stringRep: function () { return null; } | |
}) | |
]) | |
}); | |
module.exports = { | |
toTransit: function (immutableValue) { | |
return writer.write(immutableValue); | |
}, | |
fromTransit: function (ts) { | |
return reader.read(ts); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment