feat(web): integrate session management and improve API error handling

This commit is contained in:
2026-03-11 17:19:14 +08:00
parent f1932676be
commit 168a5b5613
5 changed files with 88 additions and 76 deletions

View File

@@ -1,3 +1,13 @@
export class APIError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = "APIError";
}
}
const CSMS_URL = process.env.NEXT_PUBLIC_CSMS_URL ?? "http://localhost:3001";
async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
@@ -10,11 +20,8 @@ async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
credentials: "include",
});
if (!res.ok) {
if (res.status === 401 && typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("session:expired"));
}
const text = await res.text().catch(() => res.statusText);
throw new Error(`API ${path} failed (${res.status}): ${text}`);
throw new APIError(res.status, `API ${path} failed (${res.status}): ${text}`);
}
return res.json() as Promise<T>;
}
@@ -253,4 +260,8 @@ export const api = {
},
) => apiFetch<UserRow>(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
},
setup: {
create: (data: { name: string; email: string; username: string; password: string }) =>
apiFetch<{ success: boolean }>("/api/setup", { method: "POST", body: JSON.stringify(data) }),
},
};