async function apiFetch(url, { method = 'GET', body, headers = {}, ...rest } = {}) {
const opts = {
method,
headers: { 'Content-Type': 'application/json', ...headers },
...rest,
};
if (body !== undefined) opts.body = JSON.stringify(body);
const res = await fetch(url, opts);
const data = await res.json().catch(() => null);
if (!res.ok) {
const msg = data?.message ?? data?.error ?? `HTTP ${res.status}`;
throw Object.assign(new Error(msg), { status: res.status, data });
}
return data;
}
// Usage
const user = await apiFetch('/api/users/1');
const saved = await apiFetch('/api/snippets', { method: 'POST', body: { title: 'Hi', code: '...' } });
Create a free account and build your private vault. Share publicly whenever you want.