Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 14 additions & 5 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')) {
if (res.headers['content-type'] && ~res.headers['content-type'].indexOf('image')) {
body = {
image: true
, headers: res.headers
image: true
, headers: res.headers
};
} else {
try {
body = { ...JSON.parse(body), headers: res.headers };
} catch (e) {
// parsing failed, pass raw body to end()
}
}

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()
}
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": {
topic: function () {
var callback = this.callback
, originalGet = request.get;

request.get = function (options, cb) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to somehow reset this back to what it was?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that's line 296 below

var res = { headers: { 'content-type': 'text/html' } }
, 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');
}
}
}
}).addBatch({
"When tests are over": {
topic: function () {
Expand Down