From b24219194fb6d52155af7ca4a8ee90bf398ebd0b Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 23 Sep 2026 02:45:28 +0000 Subject: [PATCH] feat: add src/api.ts --- src/api.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/api.ts diff --git a/src/api.ts b/src/api.ts new file mode 100644 index 0000000..e82b8a1 --- /dev/null +++ b/src/api.ts @@ -0,0 +1,28 @@ +export async function api(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers) + if (init.body && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json') + + const response = await fetch(path, { ...init, headers }) + if (response.status === 401) { + window.location.assign('/auth/login') + throw new Error('Authentication required') + } + if (!response.ok) { + const body = await response.text() + throw new Error(`${response.status}: ${body}`) + } + return response.json() as Promise +} + +export async function apiBlob(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers) + if (init.body && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json') + + const response = await fetch(path, { ...init, headers }) + if (response.status === 401) { + window.location.assign('/auth/login') + throw new Error('Authentication required') + } + if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`) + return response.blob() +}