export async function postJson<TReq, TRes>(
url: string,
body: TReq,
opts: Omit<RequestInit, 'method' | 'body'> = {},
): Promise<TRes> {
const r = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
...opts,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
...(opts.headers ?? {}),
},
});
if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
return r.json() as Promise<TRes>;
}
type CreateUser = { name: string; email: string };
type CreatedUser = { id: number; name: string; email: string; created_at: string };
const u = await postJson<CreateUser, CreatedUser>('/api/users', { name: 'Alice', email: 'a@x.com' });
Create a free account and build your private vault. Share publicly whenever you want.