收录 zhengquan-site 前后端完整代码:24 朝数据、24 幅权力结构图、 5 条沿革(67 节点 / 269 条细释)、44 个词条,以及部署配置与接口测试。
49 lines
1.5 KiB
JavaScript
49 lines
1.5 KiB
JavaScript
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}`);
|