import { API_BASE } from '../config'; import type { ApiErrorBody } from './types'; export class ApiError extends Error { constructor( public status: number, public body: ApiErrorBody | null, ) { super(body?.error?.message || `HTTP ${status}`); } } let accessToken: string | null = localStorage.getItem('fitos_access'); let refreshing: Promise | null = null; export function setAccessToken(token: string | null) { accessToken = token; if (token) localStorage.setItem('fitos_access', token); else localStorage.removeItem('fitos_access'); } export function getAccessToken() { return accessToken; } async function tryRefresh(): Promise { if (!refreshing) { refreshing = fetch(`${API_BASE}/auth/refresh`, { method: 'POST', credentials: 'include', }) .then(async (res) => { if (!res.ok) return false; const data = await res.json(); setAccessToken(data.accessToken); return true; }) .catch(() => false) .finally(() => { setTimeout(() => (refreshing = null), 0); }); } return refreshing; } async function fetchWithAuth( path: string, opts: { method?: string; body?: unknown } = {}, ): Promise { const isFormData = typeof FormData !== 'undefined' && opts.body instanceof FormData; const doFetch = () => fetch(`${API_BASE}${path}`, { method: opts.method || 'GET', credentials: 'include', headers: { // FormData: przeglądarka sama stawia multipart boundary ...(isFormData ? {} : { 'Content-Type': 'application/json' }), ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}), }, body: opts.body === undefined ? undefined : isFormData ? (opts.body as FormData) : JSON.stringify(opts.body), }); let res = await doFetch(); // Wylogowanie musi przejść nawet bez ważnego tokenu — odświeżanie/retre próba // przy 401 zapętlają się (handler fitos:logout znowu woła /auth/logout). const isAuthEntry = path === '/auth/refresh' || path === '/auth/login' || path === '/auth/register' || path === '/auth/logout'; if (res.status === 401 && !isAuthEntry) { const ok = await tryRefresh(); if (ok) res = await doFetch(); else { setAccessToken(null); window.dispatchEvent(new Event('fitos:logout')); } } return res; } async function toApiError(res: Response): Promise { const text = await res.text(); let json: unknown = null; if (text) { try { json = JSON.parse(text); } catch { // ciało nie-JSON (np. rate limiter, proxy) — traktujemy jako nieprzezroczysty błąd } } const body = (json ?? (text ? { error: { code: `HTTP_${res.status}`, message: text } } : null)) as ApiErrorBody | null; return new ApiError(res.status, body); } export async function api( path: string, opts: { method?: string; body?: unknown } = {}, ): Promise { const res = await fetchWithAuth(path, opts); if (!res.ok) throw await toApiError(res); const text = await res.text(); let json: unknown = null; if (text) { try { json = JSON.parse(text); } catch { // pusty/nie-JSON 2xx (np. 204) — zwracamy null } } return json as T; } /** Pobranie binarnych zasobów (zdjęcia) z tym samym bearerem i rotacją 401 co `api`. */ export async function apiBlob(path: string): Promise { const res = await fetchWithAuth(path); if (!res.ok) throw await toApiError(res); return res.blob(); }