Skip to content

Commit

Permalink
[#19, #21] Implement toJSON compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
mikepb committed Aug 19, 2013
1 parent 1b31f58 commit 44f322b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
16 changes: 14 additions & 2 deletions lib/msgpack.js
Expand Up @@ -12,12 +12,24 @@ try {
sys = require('sys');
}

var pack = mpBindings.pack;
var bpack = mpBindings.pack;
var unpack = mpBindings.unpack;

exports.pack = pack;
exports.unpack = unpack;

function pack() {
var args = arguments, that, i;
for (i = 0; i < arguments.length; i++) {
that = args[i];
if (that && typeof that === 'object' &&
typeof that.toJSON === 'function') {
args[i] = that.toJSON();
}
}
return bpack.apply(null, args);
}

var Stream = function(s) {
var self = this;

Expand All @@ -27,7 +39,7 @@ var Stream = function(s) {
self.buf = null;

// Send a message down the stream
//
//
// Allows the caller to pass additional arguments, which are passed
// faithfully down to the write() method of the underlying stream.
self.send = function(m) {
Expand Down
28 changes: 25 additions & 3 deletions test/lib/msgpack.js
Expand Up @@ -192,17 +192,17 @@ exports.msgpack = {
test.expect(4);
// Object to test with
var o = [1, 2, 3];

// Create two buffers full of packed data, 'b' and 'bb', with the latter
// containing 3 extra bytes
var b = msgpack.pack(o);
var bb = new Buffer(b.length + 3);
b.copy(bb, 0, 0, b.length);

// Expect no remaining bytes when unpacking 'b'
test.deepEqual(msgpack.unpack(b), o);
test.deepEqual(msgpack.unpack.bytes_remaining, 0);

// Expect 3 remaining bytes when unpacking 'bb'
test.deepEqual(msgpack.unpack(bb), o);
test.equal(msgpack.unpack.bytes_remaining, 3);
Expand All @@ -221,5 +221,27 @@ exports.msgpack = {
test.ok(false, e.message);
}
test.done();
},
'test toJSON compatibility' : function (test) {
var expect = { msg: 'hello world' };
var subject = { toJSON: function() { return expect; }};
test.expect(1);
test.deepEqual(expect, msgpack.unpack(msgpack.pack(subject)));
test.done();
},
'test toJSON compatibility for multiple args' : function (test) {
var expect = { msg: 'hello world' };
var subject = { toJSON: function() { return expect; }};
var subject1 = { toJSON: function() { msg: 'goodbye world' }};
test.expect(1);
test.deepEqual(expect, msgpack.unpack(msgpack.pack(subject, subject1)));
test.done();
},
'test toJSON compatibility with prototype' : function (test) {
var expect = { msg: 'hello world' };
var subject = { __proto__: { toJSON: function() { return expect; }}};
test.expect(1);
test.deepEqual(expect, msgpack.unpack(msgpack.pack(subject)));
test.done();
}
};

0 comments on commit 44f322b

Please sign in to comment.