// Created on savesnippets.com ยท https://savesnippets.com/kjtUlciDi8irvU export class HttpError extends Error { constructor(public status: number, public body: unknown, message?: string) { super(message ?? `HTTP ${status}`); } } export async function http(url: string, opts: RequestInit = {}): Promise { 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');