Add central apiFetch function
This commit is contained in:
parent
0f2b097c34
commit
8bd97c308c
53
src/lib/scripts/apiFetch.ts
Normal file
53
src/lib/scripts/apiFetch.ts
Normal 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();
|
||||
}
|
||||
}
|
@ -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>
|
||||
|
Loading…
Reference in New Issue
Block a user