Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions lib/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,17 @@ Graph.prototype.get = function () {
return;
}

body = { ...JSON.parse(body), headers: res.headers };
if (~res.headers['content-type'].indexOf('image')) {
body = {
image: true
, headers: res.headers
};
if (res.headers['content-type'] && ~res.headers['content-type'].indexOf('image')) {
body = {
image: true
, headers: res.headers
};
} else {
try {
body = { ...JSON.parse(body), headers: res.headers };
} catch (e) {
// parsing failed, pass raw body to end()
}
Comment thread
eawooten marked this conversation as resolved.
Outdated
}

self.end(body);
Expand Down Expand Up @@ -233,7 +238,11 @@ Graph.prototype.post = function() {
return;
}

body = { ...JSON.parse(body), headers: res.headers };
try {
body = { ...JSON.parse(body), headers: res.headers };
} catch (e) {
// if parsing fails, we pass the raw body to end()
Comment thread
eawooten marked this conversation as resolved.
Outdated
}
self.end(body);
})
.on('error', (err) => {
Expand Down
28 changes: 27 additions & 1 deletion tests/graph.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ var graph = require("../index")
, FBConfig = require("./config").facebook
, vows = require("vows")
, events = require("events")
, assert = require("assert");
, assert = require("assert")
, request = require("request");


var testUser1 = {}
Expand Down Expand Up @@ -277,6 +278,31 @@ vows.describe("graph.test").addBatch({
}
}
}
}).addBatch({
"Hardening JSON Parsing": {
"When receiving a non-JSON response": {
Comment thread
eawooten marked this conversation as resolved.
Outdated
topic: function() {
var callback = this.callback;
var originalGet = request.get;

request.get = function(options, cb) {
var res = { headers: { 'content-type': 'text/html' } };
var body = '{"foo": bar}'; // Malformed JSON
setImmediate(function() { cb(null, res, body); });
return { on: function() { return this; } };
};

graph.get('/me', function(err, res) {
request.get = originalGet;
callback(err, res);
});
},
"it should return an error instead of crashing": function(err, res) {
assert.isNotNull(err);
assert.equal(err.message, 'Error parsing json');
}
}
}
Comment thread
eawooten marked this conversation as resolved.
Outdated
}).addBatch({
"When tests are over": {
topic: function () {
Expand Down
Loading