文章、课程标签的默认封面
This commit is contained in:
82
schoolNewsWeb/src/utils/defaultCover.ts
Normal file
82
schoolNewsWeb/src/utils/defaultCover.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* @description 默认封面工具函数
|
||||
* @filename defaultCover.ts
|
||||
* @author system
|
||||
* @since 2025-12-24
|
||||
*/
|
||||
|
||||
import { resourceTagApi } from '@/apis/resource/resourceTag';
|
||||
import { FILE_DOWNLOAD_URL } from '@/config';
|
||||
import defaultArticleImg from '@/assets/imgs/article-default.png';
|
||||
|
||||
// 缓存标签默认封面,避免重复请求
|
||||
const tagCoverCache: Map<string, string[]> = new Map();
|
||||
|
||||
/**
|
||||
* 根据标签ID获取随机默认封面
|
||||
* @param tagID 标签ID
|
||||
* @returns Promise<string> 封面URL
|
||||
*/
|
||||
export async function getRandomDefaultCover(tagID: string | undefined): Promise<string> {
|
||||
// 如果没有tagID,返回默认封面
|
||||
if (!tagID) {
|
||||
return defaultArticleImg;
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查缓存
|
||||
if (tagCoverCache.has(tagID)) {
|
||||
const covers = tagCoverCache.get(tagID)!;
|
||||
if (covers.length > 0) {
|
||||
// 随机选择一个
|
||||
const randomIndex = Math.floor(Math.random() * covers.length);
|
||||
return covers[randomIndex];
|
||||
}
|
||||
return defaultArticleImg;
|
||||
}
|
||||
|
||||
// 从后端获取
|
||||
const result = await resourceTagApi.getDefaultCovers(tagID);
|
||||
|
||||
if (result.success && result.dataList && result.dataList.length > 0) {
|
||||
// 构建完整的URL列表
|
||||
const coverUrls = result.dataList.map((cover: any) =>
|
||||
`${FILE_DOWNLOAD_URL}${cover.coverImage}`
|
||||
);
|
||||
|
||||
// 存入缓存
|
||||
tagCoverCache.set(tagID, coverUrls);
|
||||
|
||||
// 随机选择一个
|
||||
const randomIndex = Math.floor(Math.random() * coverUrls.length);
|
||||
return coverUrls[randomIndex];
|
||||
}
|
||||
|
||||
// 如果没有配置默认封面,返回通用默认封面
|
||||
return defaultArticleImg;
|
||||
} catch (error) {
|
||||
console.error('获取标签默认封面失败:', error);
|
||||
return defaultArticleImg;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除标签封面缓存
|
||||
* @param tagID 可选,指定清除某个标签的缓存,不传则清除所有
|
||||
*/
|
||||
export function clearTagCoverCache(tagID?: string) {
|
||||
if (tagID) {
|
||||
tagCoverCache.delete(tagID);
|
||||
} else {
|
||||
tagCoverCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预加载标签默认封面到缓存
|
||||
* @param tagIDs 标签ID列表
|
||||
*/
|
||||
export async function preloadTagCovers(tagIDs: string[]) {
|
||||
const promises = tagIDs.map(tagID => getRandomDefaultCover(tagID));
|
||||
await Promise.all(promises);
|
||||
}
|
||||
Reference in New Issue
Block a user