Files
standardnotes-app-web/app/assets/javascripts/app/services/httpManager.js
2018-06-19 18:59:37 -05:00

81 lines
2.0 KiB
JavaScript

class HttpManager {
constructor($timeout, storageManager) {
// calling callbacks in a $timeout allows angular UI to update
this.$timeout = $timeout;
this.storageManager = storageManager;
}
setAuthHeadersForRequest(request) {
var token = this.storageManager.getItem("jwt");
if(token) {
request.setRequestHeader('Authorization', 'Bearer ' + token);
}
}
postAbsolute(url, params, onsuccess, onerror) {
this.httpRequest("post", url, params, onsuccess, onerror);
}
patchAbsolute(url, params, onsuccess, onerror) {
this.httpRequest("patch", url, params, onsuccess, onerror);
}
getAbsolute(url, params, onsuccess, onerror) {
this.httpRequest("get", url, params, onsuccess, onerror);
}
httpRequest(verb, url, params, onsuccess, onerror) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var response = xmlhttp.responseText;
if(response) {
try {
response = JSON.parse(response);
} catch(e) {}
}
if(xmlhttp.status >= 200 && xmlhttp.status <= 299){
this.$timeout(function(){
onsuccess(response);
})
} else {
console.error("Request error:", response);
this.$timeout(function(){
onerror(response, xmlhttp.status)
})
}
}
}.bind(this)
if(verb == "get" && Object.keys(params).length > 0) {
url = url + this.formatParams(params);
}
xmlhttp.open(verb, url, true);
this.setAuthHeadersForRequest(xmlhttp);
xmlhttp.setRequestHeader('Content-type', 'application/json');
if(verb == "post" || verb == "patch") {
xmlhttp.send(JSON.stringify(params));
} else {
xmlhttp.send();
}
}
formatParams(params) {
return "?" + Object
.keys(params)
.map(function(key){
return key+"="+encodeURIComponent(params[key])
})
.join("&")
}
}
angular.module('app').service('httpManager', HttpManager);