Created
March 22, 2015 12:46
-
-
Save mikechau/fd1587da8540de3ee9c7 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
export var getAPI = (endpoint, data = {}, opts = {}) => { | |
let url = makeUrl(endpoint, opts); | |
let request = superagent.get(url).query(data); | |
let promise = makePromise(request); | |
return promise; | |
}; | |
var makePromise = (request) => { | |
return new Promise(function(resolve, reject) { | |
request | |
.set('Accept', 'application/json') | |
.set('X-CSRF-Token', csrfToken) | |
.type('json') | |
.timeout(TIMEOUT) | |
.end(function(err, res) { | |
if (typeof res != 'undefined' && res.status === 401) { | |
reject(new UnauthorizedRequestError()); | |
} else if (typeof res != 'undefined' && res.status >= 400) { | |
let msg = `Failed to ${request.method} ${request.url} (${res.status})`; | |
let error = new SuperagentRequestError(msg); | |
error.status = res.status; | |
error.body = res.body; | |
error.res = res; | |
reject(error); | |
} else if (err) { | |
reject(new SuperagentGeneralError(err)); | |
} else { | |
resolve(res); | |
} | |
}); | |
}) | |
.catch((err) => { | |
console.log('Honeybadger report.'); | |
throw err; | |
}) | |
.catch(UnauthorizedRequestError, function(e) { | |
sessionExpiredRedirect(); | |
}); | |
}; | |
function UnauthorizedRequestError(message) {} | |
UnauthorizedRequestError.prototype = Object.create(Error.prototype); | |
function SuperagentGeneralError(message) { | |
this.name = 'SuperagentGeneralError'; | |
this.message = message || 'General error'; | |
this.timestamp = new Date(); | |
Error.captureStackTrace(this, SuperagentGeneralError); | |
} | |
SuperagentGeneralError.prototype = Object.create(Error.prototype); | |
SuperagentGeneralError.prototype.constructor = SuperagentGeneralError; | |
function SuperagentRequestError(message) { | |
this.name = 'SuperagentRequestError'; | |
this.message = message || 'Bad request'; | |
this.timestamp = new Date(); | |
} | |
SuperagentRequestError.prototype = Object.create(Error.prototype); | |
SuperagentRequestError.prototype.constructor = SuperagentRequestError; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment