export class HttpError extends Error {
constructor(public status: number, public body: unknown, message?: string) {
super(message ?? `HTTP ${status}`);
}
}
export async function http<T>(url: string, opts: RequestInit = {}): Promise<T> {
const r = await fetch(url, {
...opts,
headers: { 'Accept': 'application/json', ...(opts.headers ?? {}) },
});
const isJson = r.headers.get('content-type')?.includes('application/json');
const body = isJson ? await r.json().catch(() => null) : await r.text();
if (!r.ok) throw new HttpError(r.status, body, `HTTP ${r.status} on ${url}`);
return body as T;
}
const user = await http<{ id: number; name: string }>('/api/users/42');
Create a free account and build your private vault. Share publicly whenever you want.