Skip to content

Instantly share code, notes, and snippets.

@ipiyer
Last active November 22, 2015 22:04
Show Gist options
  • Save ipiyer/630c4cc87515cca3b378 to your computer and use it in GitHub Desktop.
Save ipiyer/630c4cc87515cca3b378 to your computer and use it in GitHub Desktop.
const Promise = require("bluebird"),
_ = require("underscore");
var request = Promise.promisifyAll(Promise.promisify(require("request")));
function httpWrap(fn) {
return function() {
let args = _.toArray(arguments);
let reqObj = _.first(args);
if (_.isString(reqObj)) {
reqObj = {
uri: reqObj,
json: true
};
} else {
// Force JSON or should throw error;
reqObj.json = true;
}
args[0] = reqObj;
let start = Date.now();
return fn.apply(request, args)
.then(res => {
let statusCode = parseInt(res.statusCode, 10);
console.log('API response time::', reqObj.uri, (Date.now() -
start) / 1000 + "s");
let content = res.body;
if (/^20[0-6]/.test(statusCode)) {
return content;
}
function MyError(content) {
this.statusCode = statusCode;
if (res.headers['content-type'] ===
"application/json") {
_.extend(this, content);
}
this.message = "Error fetchign URI: " + reqObj.uri +
" returned: " + statusCode;
this.stack = (new Error()).stack;
}
console.log("throwing....");
// This worked;
var e = new Error(content);
_.extend(e, content);
e.code = statusCode;
throw e;
// This throw warning.
//throw new MyError(content);
});
}
};
["getAsync", "postAsync", "delAsync", "putAsync"].forEach(function(fn) {
request[fn] = httpWrap(request[fn]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment