29 lines
1.1 KiB
TypeScript
29 lines
1.1 KiB
TypeScript
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()
|
|
}
|