42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
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 fetch_json<T>(url: string, init: RequestInit): Promise<PostJsonResult<T>> {
|
|
let response: Response;
|
|
try {
|
|
response = await fetch(url, init);
|
|
} 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 };
|
|
}
|
|
|
|
export function post_json<T>(
|
|
url: string,
|
|
body: unknown,
|
|
method = "POST",
|
|
headers: Record<string, string> = {},
|
|
): Promise<PostJsonResult<T>> {
|
|
return fetch_json<T>(url, {
|
|
method,
|
|
headers: { ...headers, "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
// The user's code from AskCode, sent as a bearer token
|
|
export function auth_headers() {
|
|
return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` };
|
|
}
|