增加弹幕本地缓存
This commit is contained in:
+62
-2
@@ -10,6 +10,44 @@ import type {
|
||||
DanmakuSettings,
|
||||
} from './types';
|
||||
|
||||
import {
|
||||
getDanmakuFromCache,
|
||||
saveDanmakuToCache,
|
||||
clearExpiredDanmakuCache,
|
||||
clearAllDanmakuCache,
|
||||
clearDanmakuCache,
|
||||
getDanmakuCacheStats,
|
||||
} from './cache';
|
||||
|
||||
// 初始化弹幕模块(清理过期缓存)
|
||||
let _cacheCleanupInitialized = false;
|
||||
|
||||
export function initDanmakuModule(): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (_cacheCleanupInitialized) return;
|
||||
|
||||
_cacheCleanupInitialized = true;
|
||||
|
||||
// 启动时清理一次过期缓存
|
||||
clearExpiredDanmakuCache()
|
||||
.then((count) => {
|
||||
if (count > 0) {
|
||||
console.log(`[弹幕缓存] 启动清理: 已删除 ${count} 个过期缓存`);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('[弹幕缓存] 清理失败:', error);
|
||||
});
|
||||
}
|
||||
|
||||
// 导出缓存管理函数
|
||||
export {
|
||||
clearAllDanmakuCache,
|
||||
clearDanmakuCache,
|
||||
clearExpiredDanmakuCache,
|
||||
getDanmakuCacheStats,
|
||||
};
|
||||
|
||||
// 搜索动漫
|
||||
export async function searchAnime(
|
||||
keyword: string
|
||||
@@ -98,11 +136,20 @@ export async function getEpisodes(
|
||||
}
|
||||
}
|
||||
|
||||
// 通过剧集 ID 获取弹幕
|
||||
// 通过剧集 ID 获取弹幕(优先从缓存读取)
|
||||
export async function getDanmakuById(
|
||||
episodeId: number
|
||||
): Promise<DanmakuComment[]> {
|
||||
try {
|
||||
// 1. 先尝试从缓存读取
|
||||
const cachedComments = await getDanmakuFromCache(episodeId);
|
||||
if (cachedComments) {
|
||||
console.log(`[弹幕缓存] 使用缓存: episodeId=${episodeId}, 数量=${cachedComments.length}`);
|
||||
return cachedComments;
|
||||
}
|
||||
|
||||
// 2. 缓存未命中,从 API 获取
|
||||
console.log(`[弹幕缓存] 缓存未命中,从 API 获取: episodeId=${episodeId}`);
|
||||
const url = `/api/danmaku/comment?episodeId=${episodeId}`;
|
||||
const response = await fetch(url);
|
||||
|
||||
@@ -111,7 +158,20 @@ export async function getDanmakuById(
|
||||
}
|
||||
|
||||
const data = (await response.json()) as DanmakuCommentsResponse;
|
||||
return data.comments || [];
|
||||
const comments = data.comments || [];
|
||||
|
||||
// 3. 保存到缓存
|
||||
if (comments.length > 0) {
|
||||
try {
|
||||
await saveDanmakuToCache(episodeId, comments);
|
||||
console.log(`[弹幕缓存] 已缓存: episodeId=${episodeId}, 数量=${comments.length}`);
|
||||
} catch (cacheError) {
|
||||
console.error('[弹幕缓存] 保存缓存失败:', cacheError);
|
||||
// 缓存失败不影响返回结果
|
||||
}
|
||||
}
|
||||
|
||||
return comments;
|
||||
} catch (error) {
|
||||
console.error('获取弹幕失败:', error);
|
||||
return [];
|
||||
|
||||
Reference in New Issue
Block a user