refactor(umami): 重构 Umami 数据获取逻辑并添加缓存机制

将重复的 Umami 数据获取逻辑提取为全局工具函数
添加本地缓存和并发请求处理
增加 401 错误时的自动重试机制
This commit is contained in:
afoim
2025-08-10 17:00:48 +08:00
parent d9179baa05
commit a64051177e
5 changed files with 70 additions and 22 deletions

47
public/js/umami-share.js Normal file
View File

@@ -0,0 +1,47 @@
(function (global) {
const cacheKey = 'umami-share-cache';
const cacheTTL = 3600_000; // 1h
async function fetchShareData(baseUrl, shareId) {
const cached = localStorage.getItem(cacheKey);
if (cached) {
try {
const parsed = JSON.parse(cached);
if (Date.now() - parsed.timestamp < cacheTTL) {
return parsed.value;
}
} catch {
localStorage.removeItem(cacheKey);
}
}
const res = await fetch(`${baseUrl}/api/share/${shareId}`);
if (!res.ok) {
throw new Error('获取 Umami 分享信息失败');
}
const data = await res.json();
localStorage.setItem(cacheKey, JSON.stringify({ timestamp: Date.now(), value: data }));
return data;
}
/**
* 获取 Umami 分享数据websiteId、token
* 在缓存 TTL 内复用;并用全局 Promise 避免并发请求。
* @param {string} baseUrl
* @param {string} shareId
* @returns {Promise<{websiteId: string, token: string}>}
*/
global.getUmamiShareData = function (baseUrl, shareId) {
if (!global.__umamiSharePromise) {
global.__umamiSharePromise = fetchShareData(baseUrl, shareId).catch((err) => {
delete global.__umamiSharePromise;
throw err;
});
}
return global.__umamiSharePromise;
};
global.clearUmamiShareCache = function () {
localStorage.removeItem(cacheKey);
delete global.__umamiSharePromise;
};
})(window);