const BASE = '/api'; const detailCache = new Map(); async function request(path, { ttl = 0 } = {}) { if (ttl && detailCache.has(path)) { const hit = detailCache.get(path); if (Date.now() - hit.at < ttl) return hit.value; } const res = await fetch(BASE + path, { headers: { Accept: 'application/json' } }); let body = null; try { body = await res.json(); } catch { body = null; } if (!res.ok) { const err = new Error(body?.message || `请求失败(${res.status})`); err.status = res.status; throw err; } if (ttl) detailCache.set(path, { at: Date.now(), value: body }); return body; } let bootPromise = null; export function getBootstrap() { if (!bootPromise) { bootPromise = request('/bootstrap').catch((err) => { bootPromise = null; throw err; }); } return bootPromise; } export const getDynasty = (slug) => request(`/dynasties/${encodeURIComponent(slug)}`, { ttl: 10 * 60 * 1000 }); export const getThread = (slug) => request(`/threads/${encodeURIComponent(slug)}`, { ttl: 10 * 60 * 1000 }); export const getThreads = () => request('/threads'); export const getGlossary = (params = {}) => { const q = new URLSearchParams(); if (params.q) q.set('q', params.q); if (params.category) q.set('category', params.category); const s = q.toString(); return request(`/glossary${s ? `?${s}` : ''}`); }; export const search = (q, limit = 24) => request(`/search?q=${encodeURIComponent(q)}&limit=${limit}`);