Files
shared/media-webui/src/lib/api.ts
T

55 lines
1.6 KiB
TypeScript
Raw Normal View History

import type { ApiError } from './types'
export class ApiRequestError extends Error {
status: number
payload: ApiError | null
constructor(message: string, status: number, payload: ApiError | null = null) {
super(message)
this.name = 'ApiRequestError'
this.status = status
this.payload = payload
}
}
export async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(path, {
credentials: 'include',
...init,
headers: {
...(init.body && !(init.body instanceof FormData) ? { 'content-type': 'application/json' } : {}),
...(init.headers || {}),
},
})
const contentType = response.headers.get('content-type') || ''
const payload = contentType.includes('json') ? await response.json().catch(() => null) : null
if (!response.ok) {
const error = payload as ApiError | null
throw new ApiRequestError(
error?.error || error?.message || error?.detail || response.statusText,
response.status,
error,
)
}
return (payload ?? (await response.text())) as T
}
export function get<T>(path: string) {
return request<T>(path)
}
export function post<T>(path: string, body?: unknown) {
return request<T>(path, {
method: 'POST',
...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }),
})
}
export function put<T>(path: string, body: unknown) {
return request<T>(path, { method: 'PUT', body: JSON.stringify(body) })
}
export function del<T>(path: string) {
return request<T>(path, { method: 'DELETE' })
}