feat: 添加分页功能和缓存管理,优化问答记录展示

This commit is contained in:
2026-05-23 00:44:47 +08:00
parent c48d57df14
commit cc7125e681
16 changed files with 172 additions and 243 deletions
+27 -6
View File
@@ -1,5 +1,4 @@
// server/utils/runtimeState.ts - 服务启动时间内存状态 + 问答记录 DB 读写
import { answerCache } from "~~/server/utils/cache";
import { prisma } from "~~/server/utils/db";
import { serverEnv } from "~~/server/utils/env";
@@ -29,6 +28,7 @@ export const addQaRecord = async (record: {
type: string;
options: string;
answer: string;
hash: string;
}) => {
await prisma.qaRecord.create({
data: {
@@ -36,11 +36,34 @@ export const addQaRecord = async (record: {
question: record.question,
type: record.type,
options: record.options || null,
answer: record.answer || null
answer: record.answer || null,
hash: record.hash
}
});
};
/**
* 按用户 + hash 查找 DB 缓存答案
*
* 只返回 cacheClearedAt 之后写入的记录;未存入时间或 hash 为 null 的老记录不会命中
*/
export const lookupCachedAnswer = async (
userId: string,
hash: string,
cacheClearedAt: Date | null
): Promise<string | null> => {
const record = await prisma.qaRecord.findFirst({
where: {
userId,
hash,
...(cacheClearedAt ? { createdAt: { gt: cacheClearedAt } } : {})
},
orderBy: { createdAt: "desc" },
select: { answer: true }
});
return record?.answer ?? null;
};
/**
* 从数据库分页读取指定用户的问答记录,按创建时间倒序
*/
@@ -76,13 +99,11 @@ export const getQaRecords = async (
}));
return { records, total };
};
/** 生成 `/api/stats` 响应,实时计算 uptime 和有效缓存数量 */
/** 生成 `/api/stats` 的基础运行时信息,不包含用户相关数据 */
export const getRuntimeStats = () => {
return {
version: SERVICE_VERSION,
uptime: (Date.now() - startTime) / 1000,
model: serverEnv.openAiModel,
cache_enabled: serverEnv.enableCache,
cache_size: answerCache?.size() ?? 0
model: serverEnv.openAiModel
};
};