Files
users/lib/cache-utils.ts
v0 2408d50cb0 refactor: overhaul UI for streamlined user experience
Redesign navigation, home overview, user portrait, and valuation pages
with improved functionality and responsive design.

Co-authored-by: null <4804959+fnvtk@users.noreply.github.com>
2025-07-18 13:47:12 +00:00

85 lines
1.5 KiB
TypeScript

/**
* 简单的内存缓存实现
*/
interface CacheItem<T> {
value: T
expiry: number
}
class MemoryCache {
private cache: Map<string, CacheItem<any>> = new Map()
/**
* 获取缓存项
* @param key 缓存键
* @returns 缓存值或undefined
*/
get<T>(key: string): T | undefined {
const item = this.cache.get(key)
if (!item) {
return undefined
}
if (Date.now() > item.expiry) {
this.cache.delete(key)
return undefined
}
return item.value
}
/**
* 设置缓存项
* @param key 缓存键
* @param value 缓存值
* @param ttlMs 过期时间(毫秒)
*/
set<T>(key: string, value: T, ttlMs: number): void {
this.cache.set(key, {
value,
expiry: Date.now() + ttlMs,
})
}
/**
* 删除缓存项
* @param key 缓存键
*/
delete(key: string): void {
this.cache.delete(key)
}
/**
* 清空所有缓存
*/
clear(): void {
this.cache.clear()
}
}
export const memoryCache = new MemoryCache()
/**
* 带缓存的数据获取函数
* @param key 缓存键
* @param fetchFn 获取数据的函数
* @param ttlMs 缓存过期时间(毫秒)
* @returns Promise<T>
*/
export async function fetchWithCache<T>(
key: string,
fetchFn: () => Promise<T>,
ttlMs = 60000, // 默认1分钟
): Promise<T> {
const cachedData = memoryCache.get<T>(key)
if (cachedData !== undefined) {
return cachedData
}
const data = await fetchFn()
memoryCache.set(key, data, ttlMs)
return data
}