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:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user