Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
1.9 kB · 74 lines
TypeScript
at master
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475const JSON_HEADERS = { "content-type": "application/json" };
export class ApiFailure extends Error { status: number;
constructor(status: number, message: string) { super(message); this.status = status; }}
export async function api<T>( path: string, init: RequestInit = {},): Promise<T> { const response = await fetch(path, { ...init, headers: init.body instanceof FormData ? init.headers : { ...JSON_HEADERS, ...init.headers }, }); if (!response.ok) { let message = `${response.status} ${response.statusText}`; try { const payload = (await response.json()) as { error?: string }; message = payload.error ?? message; } catch { // The fallback status text is already useful. } throw new ApiFailure(response.status, message); } if (response.status === 204) { return undefined as T; } return (await response.json()) as T;}
export function post<T>(path: string, body?: unknown) { return api<T>(path, { method: "POST", body: body === undefined ? undefined : JSON.stringify(body), });}
export function patch<T>(path: string, body: unknown) { return api<T>(path, { method: "PATCH", body: JSON.stringify(body) });}
export function put<T>(path: string, body: unknown) { return api<T>(path, { method: "PUT", body: JSON.stringify(body) });}
export function remove<T>(path: string) { return api<T>(path, { method: "DELETE" });}
export async function uploadAsset( file: File | Blob, kind: string, filename?: string, metadata?: Record<string, unknown>,) { const form = new FormData(); form.append("kind", kind); if (metadata) { form.append("metadata", JSON.stringify(metadata)); } form.append("file", file, filename ?? (file instanceof File ? file.name : "asset")); return api<import("./types").Asset>("/api/assets", { method: "POST", body: form, });}