2026-07-25 01:11:42 +00:00
|
|
|
// Thin fetch wrapper for the podsteadr API (session cookie auth).
|
2026-07-10 19:06:43 +00:00
|
|
|
|
|
|
|
|
export class ApiError extends Error {
|
|
|
|
|
constructor(public status: number, message: string) {
|
|
|
|
|
super(message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T> {
|
|
|
|
|
const res = await fetch(path, {
|
|
|
|
|
method,
|
|
|
|
|
credentials: 'same-origin',
|
|
|
|
|
headers: {
|
|
|
|
|
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
|
|
|
...headers,
|
|
|
|
|
},
|
|
|
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
|
|
|
});
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
let message = res.statusText;
|
|
|
|
|
try {
|
|
|
|
|
message = ((await res.json()) as { error?: string }).error ?? message;
|
|
|
|
|
} catch {
|
|
|
|
|
/* keep statusText */
|
|
|
|
|
}
|
|
|
|
|
throw new ApiError(res.status, message);
|
|
|
|
|
}
|
|
|
|
|
return (await res.json()) as T;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const api = {
|
|
|
|
|
get: <T>(path: string) => request<T>('GET', path),
|
|
|
|
|
post: <T>(path: string, body?: unknown, headers?: Record<string, string>) =>
|
|
|
|
|
request<T>('POST', path, body, headers),
|
|
|
|
|
put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body),
|
|
|
|
|
delete: <T>(path: string) => request<T>('DELETE', path),
|
|
|
|
|
};
|