Skip to content

Commit

Permalink
[fix] Properly handle JSON.stringify errors (#84)
Browse files Browse the repository at this point in the history
JSON.stringify method throws when passed a circular object.
  • Loading branch information
darrachequesne committed Feb 28, 2018
1 parent dc4f475 commit 92c530d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
20 changes: 17 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,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 @@ -128,8 +130,7 @@ Encoder.prototype.encode = function(obj, callback){

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 @@ -166,13 +167,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
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 92c530d

Please sign in to comment.