feat(web): add apiFetch with typed error envelope

Wraps fetch, parses JSON, and throws ApiError{code,message,status}
on non-2xx. Degrades to {code:'unknown'} when the error body is not
the expected envelope shape.
This commit is contained in:
2026-04-22 15:56:15 -04:00
parent e31242b57f
commit 4d1a7f8b93
2 changed files with 76 additions and 0 deletions
+19
View File
@@ -14,3 +14,22 @@ export type LoginResponse = {
token: string;
user: User;
};
export async function apiFetch(path: string, init?: RequestInit): Promise<unknown> {
const res = await fetch(path, {
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
...init
});
const body = res.status === 204 ? null : await res.json().catch(() => null);
if (!res.ok) {
const envelope = body && (body as { error?: { code?: string; message?: string } }).error;
const err: ApiError = {
code: envelope?.code ?? 'unknown',
message: envelope?.message ?? res.statusText,
status: res.status
};
throw err;
}
return body;
}