import { clearSession, getAccessToken, getRefreshToken, getStoredUser, setSession, } from '../auth/storage' import { apiUrl } from '../config/apiBase' async function readDetail(res) { try { const data = await res.json() const d = data.detail if (typeof d === 'string') return d if (Array.isArray(d)) return d.map((e) => e.msg || JSON.stringify(e)).join(' ') return data.message || res.statusText } catch { return res.statusText || 'Request failed' } } async function postRefresh() { const rt = getRefreshToken() if (!rt) return null const res = await fetch(apiUrl('/users/refresh'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: rt }), }) if (!res.ok) return null const text = await res.text() return text ? JSON.parse(text) : null } function redirectToLogin() { clearSession() if (typeof window !== 'undefined') { window.location.assign('/login') } } /** * @param {string} path * @param {RequestInit & { auth?: boolean }} options - set auth: true to send Bearer and refresh on 401 */ export async function apiJson(path, options = {}) { const { auth = false, ...fetchOpts } = options function buildHeaders() { const h = { 'Content-Type': 'application/json', ...(fetchOpts.headers || {}), } if (auth) { const access = getAccessToken() if (access) { h.Authorization = `Bearer ${access}` } } return h } const url = apiUrl(path) let res = await fetch(url, { ...fetchOpts, headers: buildHeaders(), }) if (res.status === 401 && auth) { const data = await postRefresh() if (data?.access_token && data?.refresh_token) { setSession({ access_token: data.access_token, refresh_token: data.refresh_token, user: getStoredUser(), }) res = await fetch(url, { ...fetchOpts, headers: buildHeaders(), }) } else { redirectToLogin() throw new Error('Session expired') } } if (!res.ok) { if (res.status === 401 && auth) { redirectToLogin() } throw new Error(await readDetail(res)) } if (res.status === 204) return null const text = await res.text() return text ? JSON.parse(text) : null }