diff options
author | HampusM <hampus@hampusmat.com> | 2021-07-06 13:07:07 +0200 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2021-07-06 13:07:07 +0200 |
commit | 39c38c737114dc7f946b1895b2a4ba27a5546c60 (patch) | |
tree | 61344a90155845d08c4811da16e6f90504da2625 /packages/client/src/util/fetch.ts | |
parent | 4102adab527ccc4f6d8ac210118dea21177c212d (diff) |
Migrated frontend to typescript
Diffstat (limited to 'packages/client/src/util/fetch.ts')
-rw-r--r-- | packages/client/src/util/fetch.ts | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/packages/client/src/util/fetch.ts b/packages/client/src/util/fetch.ts new file mode 100644 index 0000000..54f5afd --- /dev/null +++ b/packages/client/src/util/fetch.ts @@ -0,0 +1,37 @@ +import { Ref } from "vue"; + +export default async function(endpoint: string, fetch_failed: Ref<string | null>, is_loading: Ref<boolean>, data_name: string) { + 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; +}; |