/**
* 管理员路由:日志查询 API + 自包含 HTML 面板。
*/
import type { FastifyInstance } from "fastify";
import { logStore } from "./store.js";
const PANEL_HTML = `
lpt-ai · 管理面板
暂无请求记录
`;
export async function adminRoutes(app: FastifyInstance): Promise {
// —— 面板页面 ——
app.get("/admin", async (_request, reply) => {
return reply.type("text/html; charset=utf-8").send(PANEL_HTML);
});
// —— 日志列表 ——
app.get<{ Querystring: { endpoint?: string } }>("/admin/logs", async (request) => {
const endpoint = request.query.endpoint || undefined;
const summaries = logStore.list(endpoint);
const stats = {
total: summaries.length,
ok: summaries.filter((s) => s.status >= 200 && s.status < 300).length,
err: summaries.filter((s) => s.status < 200 || s.status >= 300).length,
avgMs: summaries.length > 0
? Math.round(summaries.reduce((a, s) => a + s.durationMs, 0) / summaries.length)
: 0,
endpoints: logStore.endpoints(),
};
return { logs: summaries, stats };
});
// —— 日志详情 ——
app.get<{ Params: { id: string } }>("/admin/logs/:id", async (request, reply) => {
const id = parseInt(request.params.id, 10);
if (isNaN(id)) {
return reply.status(400).send({ error: "无效 ID" });
}
const entry = logStore.get(id);
if (!entry) {
return reply.status(404).send({ error: "日志不存在" });
}
return entry;
});
// —— 清空日志 ——
app.delete("/admin/logs", async () => {
logStore.clear();
return { ok: true };
});
}