Use saved code
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
export type PostJsonResult<T> =
|
||||
| { ok: true; data: T }
|
||||
// status is 0 when the request never reached the server
|
||||
| { ok: false; status: number; error: string };
|
||||
|
||||
export async function post_json<T>(url: string, body: unknown, method = "POST"): Promise<PostJsonResult<T>> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
|
||||
const data = response.status === 204 ? undefined : await response.json().catch(() => undefined);
|
||||
if (!response.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
status: response.status,
|
||||
error: data?.error ?? `Request failed with status ${response.status}`,
|
||||
};
|
||||
}
|
||||
return { ok: true, data: data as T };
|
||||
}
|
||||
Reference in New Issue
Block a user