36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
const BASE = import.meta.env.DEV ? 'http://127.0.0.1:8801' : '';
|
|
|
|
let token = localStorage.getItem('hub_token') ?? '';
|
|
|
|
export function setToken(value: string): void {
|
|
token = value.trim();
|
|
if (token) localStorage.setItem('hub_token', token);
|
|
else localStorage.removeItem('hub_token');
|
|
}
|
|
|
|
async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
const response = await fetch(BASE + path, {
|
|
method,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
},
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
const data = (await response.json().catch(() => ({}))) as Record<string, unknown>;
|
|
if (!response.ok) {
|
|
throw new Error(typeof data.detail === 'string' ? data.detail : `${response.status} ${response.statusText}`);
|
|
}
|
|
return data as T;
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string) => call<T>('GET', path),
|
|
post: <T>(path: string, body?: unknown) => call<T>('POST', path, body ?? {}),
|
|
del: <T>(path: string) => call<T>('DELETE', path),
|
|
};
|
|
|
|
export function errorText(error: unknown): string {
|
|
return error instanceof Error ? error.message : String(error);
|
|
}
|