Files
family_budget/frontend/src/api/client.ts
Anton 975f2c4fd2 feat: adds PDF import with conversion to JSON 1.0
- Accept only PDF and JSON files in import modal and API
- Convert PDF statements to JSON 1.0 via LLM (OpenAI-compatible)
- Use multipart/form-data for file upload (multer, 15 MB limit)
- Add LLM_API_KEY and LLM_API_BASE_URL for configurable LLM endpoint
- Update ImportModal to validate type and send FormData
- Add postFormData to API client for file upload
2026-03-13 13:38:02 +03:00

111 lines
2.6 KiB
TypeScript

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) {
let body: ApiError;
try {
body = await res.json();
} catch {
body = { error: 'UNAUTHORIZED', message: 'Сессия истекла' };
}
if (!url.includes('/api/auth/login')) {
onUnauthorized?.();
}
throw new ApiException(401, body);
}
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();
}
async function requestFormData<T>(url: string, formData: FormData): Promise<T> {
const res = await fetch(url, {
method: 'POST',
body: formData,
credentials: 'include',
// Do not set Content-Type — browser sets multipart/form-data with boundary
});
if (res.status === 401) {
let body: ApiError;
try {
body = await res.json();
} catch {
body = { error: 'UNAUTHORIZED', message: 'Сессия истекла' };
}
if (!url.includes('/api/auth/login')) {
onUnauthorized?.();
}
throw new ApiException(401, body);
}
if (!res.ok) {
let body: ApiError;
try {
body = await res.json();
} catch {
body = { error: 'UNKNOWN', message: res.statusText };
}
throw new ApiException(res.status, body);
}
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,
}),
postFormData: <T>(url: string, formData: FormData) =>
requestFormData<T>(url, formData),
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) }),
delete: <T>(url: string) =>
request<T>(url, { method: 'DELETE' }),
};