feat: add src/api.ts

This commit is contained in:
Admin 2026-09-23 02:45:28 +00:00
parent c238f77451
commit b24219194f

28
src/api.ts Normal file
View File

@ -0,0 +1,28 @@
export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
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<T>
}
export async function apiBlob(path: string, init: RequestInit = {}): Promise<Blob> {
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()
}