Files
users/lib/cache-utils.ts

85 lines
1.5 KiB
TypeScript
Raw Normal View History

/**
*
*/
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
}