Last active
November 22, 2015 22:04
-
-
Save ipiyer/630c4cc87515cca3b378 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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