feat: add src/api.ts
This commit is contained in:
parent
c238f77451
commit
b24219194f
28
src/api.ts
Normal file
28
src/api.ts
Normal 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()
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user