2025-02-17 13:26:10 +01:00
|
|
|
export async function api<T>(url: string, restful_token?: string, post?: boolean, body?: BodyInit): Promise<T> {
|
|
|
|
let fetched: Promise<Response>;
|
|
|
|
if (post) {
|
|
|
|
fetched = fetch(url, {
|
|
|
|
method: "POST",
|
|
|
|
headers: {
|
|
|
|
"Authorization": `Bearer ${restful_token}`,
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
body,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
fetched = (restful_token ? fetch(url, {headers: {"Authorization": `Bearer ${restful_token}`}}) : fetch(url));
|
|
|
|
}
|
2025-02-16 17:05:02 +01:00
|
|
|
|
2025-02-17 13:26:10 +01:00
|
|
|
return fetched.then(async response => {
|
|
|
|
if (!response.ok) {
|
|
|
|
console.error(response.status, response.statusText);
|
|
|
|
throw new Error("Request failed :(");
|
|
|
|
}
|
2024-04-27 18:45:18 +02:00
|
|
|
|
2025-02-17 13:26:10 +01:00
|
|
|
return response.json() as Promise<T>;
|
|
|
|
});
|
2023-05-07 02:13:48 +02:00
|
|
|
}
|