Use saved code

This commit is contained in:
2026-10-29 16:26:36 -03:00
parent 08f10022e0
commit 7608408e59
3 changed files with 64 additions and 23 deletions
+27
View File
@@ -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 };
}