Skip to content

Instantly share code, notes, and snippets.

@markcode
Last active December 21, 2015 03:58
Show Gist options
  • Save markcode/6245957 to your computer and use it in GitHub Desktop.
Save markcode/6245957 to your computer and use it in GitHub Desktop.
Codec prototype for serializing messages in: json, msgpack or msgpack-js.
// require these modules: 'msgpack' (binding), 'msgpack-js' (pure javascript), JSON node.js built in function.
// config
var config = [];
config["messenger_codec"] = 'json'; // json, msgpack, msgpack-js
// codec for messenger to use: json, msgpack, msgpack-js.
var Codec = function() { };
if ( config["messenger_codec"] === 'msgpack' ) {
var msgpack = require('msgpack');
Codec.prototype.encode = function(m) { return msgpack.pack(m); };
Codec.prototype.decode = function(m) { return msgpack.unpack(m); };
} else if ( config["messenger_codec"] === 'msgpack-js' ) {
var msgpack = require('msgpack-js');
Codec.prototype.encode = function(m) { return msgpack.encode(m); };
Codec.prototype.decode = function(m) { return msgpack.decode(m); };
} else {
// json
Codec.prototype.encode = function(m) { return JSON.stringify(m); };
Codec.prototype.decode = function(m) { return JSON.parse(m); };
}
// to use
var codec = new Codec(); // use: codec.encode(message), codec.decode(message).
var mcodexEncode = codec.encode(msg); // encode message
var mcodexDecode = codec.decode(msg); // decode message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment