aboutsummaryrefslogtreecommitdiff
path: root/packages/client/src/util
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2021-06-09 17:37:43 +0200
committerHampusM <hampus@hampusmat.com>2021-06-09 17:37:43 +0200
commit75e8ae6ebd9df23275fb14eea88da0b56d006313 (patch)
treecd8a261f856e2177626272e7018041be3102304b /packages/client/src/util
parentdae7377188242e8dbc18f029bc97b7def9acb13c (diff)
Frontend has proper error handling & api fetching is in it's own file
Diffstat (limited to 'packages/client/src/util')
-rw-r--r--packages/client/src/util/fetch.js35
1 files changed, 35 insertions, 0 deletions
diff --git a/packages/client/src/util/fetch.js b/packages/client/src/util/fetch.js
new file mode 100644
index 0000000..a6a43b0
--- /dev/null
+++ b/packages/client/src/util/fetch.js
@@ -0,0 +1,35 @@
+export default async function(endpoint, fetch_failed, is_loading, data_name) {
+ const fetch_timeout = setTimeout(() => {
+ if(!fetch_failed.value) {
+ fetch_failed.value = `Failed to fetch ${data_name} data.`;
+ is_loading.value = false;
+ }
+ }, 5000);
+
+ const data_req = await fetch(`${window.location.protocol}//${window.location.host}/api/v1/${endpoint}`).catch(() => {
+ if(!fetch_failed.value) {
+ fetch_failed.value = `Failed to fetch ${data_name} data.`;
+ is_loading.value = false;
+ clearTimeout(fetch_timeout);
+ }
+ return null;
+ });
+
+ if(data_req !== null) {
+ const data = await data_req.json().catch(() => {
+ fetch_failed.value = "Failed to parse server response.";
+ });
+
+ if(data_req.ok) {
+ clearTimeout(fetch_timeout);
+ is_loading.value = false;
+ return data.data;
+ } else {
+ fetch_failed.value = `Failed to fetch ${data_name} data.`;
+ }
+ }
+
+ clearTimeout(fetch_timeout);
+ is_loading.value = false;
+ return null;
+};