Skip to content

Commit

Permalink
Merge pull request #1 from Sirach99/double-callback-fix
Browse files Browse the repository at this point in the history
Fix error handling in get and post methods
  • Loading branch information
Sirach99 authored Jul 28, 2024
2 parents 29e9a52 + 768fafb commit 5f05a6b
Showing 1 changed file with 42 additions and 22 deletions.
64 changes: 42 additions & 22 deletions lib/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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;
});
};

Expand All @@ -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
Expand Down

0 comments on commit 5f05a6b

Please sign in to comment.