12 lines
737 B
TypeScript
12 lines
737 B
TypeScript
export async function api(path: string, method = 'GET', body?: unknown): Promise<any> {
|
|
const response = await fetch('/api' + path, { method, headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
if (!response.ok) {
|
|
let detail = response.statusText;
|
|
try { const value = await response.json(); detail = typeof value.detail === 'string' ? value.detail : JSON.stringify(value.detail); } catch { /* server returned no JSON */ }
|
|
throw new Error(detail);
|
|
}
|
|
return response.json();
|
|
}
|
|
export const post = (path: string, body?: unknown) => api(path, 'POST', body);
|
|
export const put = (path: string, body: unknown) => api(path, 'PUT', body);
|