Skip to content

Commit

Permalink
Refactor(main): Moved response handling to function
Browse files Browse the repository at this point in the history
  • Loading branch information
fvdm committed Sep 5, 2016
1 parent 02bc29b commit 9590f0d
Showing 1 changed file with 52 additions and 33 deletions.
85 changes: 52 additions & 33 deletions requestbin.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,57 @@ var config = {
};


/**
* Process response
*
* argument order is to prevent callback
* handler detection in code parsers
*
* @callback callback
* @param res {object} - httpreq response
* @param err {Error|null} - httpreq error
* @param callback {function} - `function (err, data) {}`
* @return {void}
*/

function processResponse (res, err, callback) {
var data = res && res.body || null;
var error = null;

if (err) {
error = new Error ('request failed');
error.error = err;
callback (error);
return;
}

if (res && res.statusCode >= 300) {
error = new Error ('HTTP error');
return;
}

try {
data = JSON.parse (data);
} catch (e) {
error = new Error ('invalid response');
}

if (error) {
error.httpCode = res.statusCode;
error.request = options;
error.response = {
headers: res.headers,
body: data
};

callback (error);
return;
}

callback (null, data);
}


/**
* Communicate with API
*
Expand Down Expand Up @@ -47,39 +98,7 @@ function talk (method, path, props, callback) {
}

httpreq.doRequest (options, function (err, res) {
var data = res && res.body || null;
var error = null;

if (err) {
error = new Error ('request failed');
error.error = err;
callback (error);
return;
}

if (res && res.statusCode >= 300) {
error = new Error ('HTTP error');
return;
}

try {
data = JSON.parse (data);
} catch (e) {
error = new Error ('invalid response');
}

if (error) {
error.httpCode = res.statusCode;
error.request = options;
error.response = {
headers: res.headers,
body: data
};
callback (error);
return;
}

callback (null, data);
processResponse (res, err, callback);
});
}

Expand Down

0 comments on commit 9590f0d

Please sign in to comment.