From bd148897f81553eb081eceb6c0eface84cb332c6 Mon Sep 17 00:00:00 2001 From: Axolotle Date: Sun, 12 Jul 2020 19:02:34 +0200 Subject: [PATCH] add handlers for response and errors & api simple get method and version getter --- app/src/helpers/api.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/app/src/helpers/api.js b/app/src/helpers/api.js index 6e2bfca7..02d53c81 100644 --- a/app/src/helpers/api.js +++ b/app/src/helpers/api.js @@ -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 { options: { 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) { return fetch('/api/login', { method: 'POST', @@ -34,5 +54,10 @@ export default { logout() { return fetch('/api/logout', this.options).then(response => (response.ok)) + }, + + getVersion() { + return fetch('/api/versions', this.options) + .then(response => handleResponse(response)) } }