Add central apiFetch function

This commit is contained in:
Fred Boniface 2024-04-30 11:03:13 +01:00
parent 0f2b097c34
commit 8bd97c308c
2 changed files with 54 additions and 1 deletions

View File

@ -0,0 +1,53 @@
import { dev } from '$app/environment';
import { uuid } from '$lib/stores/uuid';
import type { Unsubscriber } from 'svelte/store';
const testUrl: string = 'http://localhost:8460';
const prodUrl: string = 'https://owlboard.info';
function getUrlString(): string {
if (dev) {
console.info('DEVMODE active, using testing URL: ', testUrl);
return testUrl;
}
return prodUrl;
}
export async function apiGet(path: string): Promise<any> {
let uuidString: string = '';
let unsubscribe: Unsubscriber;
try {
unsubscribe = uuid.subscribe((value) => {
uuidString = value;
});
} catch (err) {
throw new Error('Unable to read UUID');
}
const options = {
method: 'GET',
headers: {
uuid: uuidString
}
};
try {
const res = await fetch(getUrlString() + path, options);
if (!res.ok) {
throw new Error('Network response not ok');
}
const contentType = res.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Invalid response. Require JSON.');
}
return await res.json();
} catch (err) {
console.error('Error fetching data:', err);
throw err;
} finally {
unsubscribe();
}
}

View File

@ -32,7 +32,7 @@
<!-- Render a newline if any of the icons is to appear -->
{#if serviceDetails.firstClass || serviceDetails.catering || serviceDetails.sleeper || serviceDetails.vstp}
<br>
<br />
{/if}
<style>