feat: creats frontend for the project

This commit is contained in:
vakabunga
2026-03-02 00:33:09 +03:00
parent 4d67636633
commit cd56e2bf9d
37 changed files with 3762 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
import type { ApiError } from '@family-budget/shared';
let onUnauthorized: (() => void) | null = null;
export function setOnUnauthorized(cb: () => void) {
onUnauthorized = cb;
}
export class ApiException extends Error {
constructor(
public status: number,
public body: ApiError,
) {
super(body.message);
}
}
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
},
credentials: 'include',
});
if (res.status === 401) {
onUnauthorized?.();
throw new ApiException(401, { error: 'UNAUTHORIZED', message: 'Сессия истекла' });
}
if (!res.ok) {
let body: ApiError;
try {
body = await res.json();
} catch {
body = { error: 'UNKNOWN', message: res.statusText };
}
throw new ApiException(res.status, body);
}
if (res.status === 204) return undefined as T;
return res.json();
}
export const api = {
get: <T>(url: string) => request<T>(url),
post: <T>(url: string, body?: unknown) =>
request<T>(url, {
method: 'POST',
body: body != null ? JSON.stringify(body) : undefined,
}),
put: <T>(url: string, body: unknown) =>
request<T>(url, { method: 'PUT', body: JSON.stringify(body) }),
patch: <T>(url: string, body: unknown) =>
request<T>(url, { method: 'PATCH', body: JSON.stringify(body) }),
};