Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix] Properly handle JSON.stringify errors #84

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 26 additions & 5 deletions index.js
Expand Up @@ -114,6 +114,8 @@ exports.Decoder = Decoder;

function Encoder() {}

var ERROR_PACKET = exports.ERROR + '"encode error"';

/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
Expand All @@ -125,16 +127,22 @@ function Encoder() {}
*/

Encoder.prototype.encode = function(obj, callback){
if ((obj.type === exports.EVENT || obj.type === exports.ACK) && hasBin(obj.data)) {
obj.type = obj.type === exports.EVENT ? exports.BINARY_EVENT : exports.BINARY_ACK;

if (obj.type === exports.EVENT || obj.type === exports.ACK) {
try {
if (hasBin(obj.data)) {
obj.type = obj.type === exports.EVENT ? exports.BINARY_EVENT : exports.BINARY_ACK;
}
} catch (e) {
callback([ERROR_PACKET]);
}
}

debug('encoding packet %j', obj);

if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
encodeAsBinary(obj, callback);
}
else {
} else {
var encoding = encodeAsString(obj);
callback([encoding]);
}
Expand Down Expand Up @@ -171,13 +179,26 @@ function encodeAsString(obj) {

// json data
if (null != obj.data) {
str += JSON.stringify(obj.data);
var payload = tryStringify(obj.data);
if (payload !== false) {
str += payload;
} else {
return ERROR_PACKET;
}
}

debug('encoded %j as %s', obj, str);
return str;
}

function tryStringify(str) {
try {
return JSON.stringify(str);
} catch(e){
return false;
}
}

/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
Expand Down
20 changes: 18 additions & 2 deletions test/parser.js
@@ -1,8 +1,6 @@
var parser = require('../index.js');
var expect = require('expect.js');
var helpers = require('./helpers.js');
var encode = parser.encode;
var decode = parser.decode;

describe('parser', function(){

Expand Down Expand Up @@ -61,6 +59,24 @@ describe('parser', function(){
});
});

it('properly handles circular objects', function() {
var a = {};
a.b = a;

var data = {
type: parser.EVENT,
data: a,
id: 1,
nsp: '/'
}

var encoder = new parser.Encoder();

encoder.encode(data, function(encodedPackets) {
expect(encodedPackets[0]).to.be('4"encode error"');
});
});

it('decodes a bad binary packet', function(){
try {
var decoder = new parser.Decoder();
Expand Down