diff --git a/lib/graph.js b/lib/graph.js index 835136b..2dc3111 100644 --- a/lib/graph.js +++ b/lib/graph.js @@ -177,14 +177,16 @@ Graph.prototype.end = function (body) { Graph.prototype.get = function () { var self = this; + let callbackCalled = false; - return request.get(this.options, function(err, res, body) { + return request.get(this.options, (err, res, body) => { if (err) { - self.callback({ - message: 'Error processing https request' - , exception: err - }, null); - + handleRequestError( + self, + callbackCalled, + { message: 'Error processing https request in get', exception: err }, + ); + callbackCalled = true; return; } @@ -196,11 +198,13 @@ Graph.prototype.get = function () { } self.end(body); - }).on('error', function(err) { - self.callback({ - message: 'Error processing https request' - , exception: err - }, null); + }).on('error', (err) => { + handleRequestError( + self, + callbackCalled, + { message: 'Error processing https request in get', exception: err }, + ); + callbackCalled = true; }); }; @@ -215,28 +219,44 @@ Graph.prototype.post = function() { , postData = qs.stringify(this.postData); this.options.body = postData; + let callbackCalled = false; - return request(this.options, function (err, res, body) { + return request(this.options, (err, res, body) => { if (err) { - self.callback({ - message: 'Error processing https request' - , exception: err - }, null); - + handleRequestError( + self, + callbackCalled, + { message: 'Error processing https request in post', exception: err }, + ); + callbackCalled = true; return; } self.end(body); }) - .on('error', function(err) { - self.callback({ - message: 'Error processing https request' - , exception: err - }, null); + .on('error', (err) => { + handleRequestError( + self, + callbackCalled, + { message: 'Error processing https request in post', exception: err }, + ); + callbackCalled = true; }); }; +/** + * Handles request errors + * @param {object} self - the graph object + * @param {boolean} callbackCalled - whether the callback has been called + * @param {object} error - the error object + */ +function handleRequestError(self, callbackCalled, error) { + if (!callbackCalled) { + self.callback(error); + } +} + /** * Accepts an url an returns facebook * json data to the callback provided