aboutsummaryrefslogtreecommitdiff
path: root/packages/client/src/util/fetch.ts
blob: a67014a03fc07ec8cde5001fc8e3330f1fe12ccb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Ref } from "vue";

export default async function(endpoint: string, fetch_failed: Ref<string | null>, is_loading: Ref<boolean>, data_name: string): Promise<unknown | null> {
	const fetch_timeout = setTimeout(() => {
		if(!fetch_failed.value) {
			fetch_failed.value = `Failed to fetch ${data_name} data.`;
			is_loading.value = false;
		}
	}, 5000);

	const res = 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(res !== null && res.ok) {
		const data: Record<string, unknown> | null = await res.json().catch(() => {
			fetch_failed.value = "Failed to parse server response.";
		});

		if(data) {
			clearTimeout(fetch_timeout);
			is_loading.value = false;
			return data.data;
		}
	}

	fetch_failed.value = `Failed to fetch ${data_name} data.`;

	clearTimeout(fetch_timeout);
	is_loading.value = false;
	return null;
}