add handlers for response and errors & api simple get method and version getter

This commit is contained in:
Axolotle 2020-07-12 19:02:34 +02:00
parent 9232961b61
commit bd148897f8

View file

@ -9,6 +9,18 @@ function objectToParams(object) {
} }
function handleResponse(response, type = 'json') {
return response.ok ? response[type]() : handleErrors(response)
}
function handleErrors(response) {
if (response.status == 401) {
throw new Error('Unauthorized');
}
}
export default { export default {
options: { options: {
credentials: 'include', credentials: 'include',
@ -24,6 +36,14 @@ export default {
} }
}, },
get(uri) {
return fetch('/api/' + uri, this.options)
.then(response => handleResponse(response))
.catch(err => {
console.log(err)
})
},
login(password) { login(password) {
return fetch('/api/login', { return fetch('/api/login', {
method: 'POST', method: 'POST',
@ -34,5 +54,10 @@ export default {
logout() { logout() {
return fetch('/api/logout', this.options).then(response => (response.ok)) return fetch('/api/logout', this.options).then(response => (response.ok))
},
getVersion() {
return fetch('/api/versions', this.options)
.then(response => handleResponse(response))
} }
} }