84 lines
2.3 KiB
TypeScript
84 lines
2.3 KiB
TypeScript
|
|
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_admin_access');
|
||
|
|
let refreshing: Promise<boolean> | null = null;
|
||
|
|
|
||
|
|
export function setAccessToken(token: string | null) {
|
||
|
|
accessToken = token;
|
||
|
|
if (token) localStorage.setItem('fitos_admin_access', token);
|
||
|
|
else localStorage.removeItem('fitos_admin_access');
|
||
|
|
}
|
||
|
|
|
||
|
|
export function getAccessToken() {
|
||
|
|
return accessToken;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function tryRefresh(): Promise<boolean> {
|
||
|
|
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;
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function api<T>(path: string, opts: { method?: string; body?: unknown } = {}): Promise<T> {
|
||
|
|
const doFetch = () =>
|
||
|
|
fetch(`${API_BASE}${path}`, {
|
||
|
|
method: opts.method || 'GET',
|
||
|
|
credentials: 'include',
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
||
|
|
},
|
||
|
|
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||
|
|
});
|
||
|
|
|
||
|
|
let res = await doFetch();
|
||
|
|
|
||
|
|
if (res.status === 401 && path !== '/auth/refresh' && path !== '/auth/login' && path !== '/auth/register') {
|
||
|
|
const ok = await tryRefresh();
|
||
|
|
if (ok) res = await doFetch();
|
||
|
|
else {
|
||
|
|
setAccessToken(null);
|
||
|
|
window.dispatchEvent(new Event('fitos:logout'));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
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
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (!res.ok) {
|
||
|
|
const body = (json ?? (text ? { error: { code: `HTTP_${res.status}`, message: text } } : null)) as ApiErrorBody | null;
|
||
|
|
throw new ApiError(res.status, body);
|
||
|
|
}
|
||
|
|
return json as T;
|
||
|
|
}
|