| 5 | } |
| 6 | |
| 7 | class Cache { |
| 8 | private static instance: Cache; |
| 9 | private cache = new Map<string, CacheItem<unknown>>(); |
| 10 | |
| 11 | private constructor() {} |
| 12 | |
| 13 | static getInstance(): Cache { |
| 14 | if (!Cache.instance) { |
| 15 | Cache.instance = new Cache(); |
| 16 | } |
| 17 | return Cache.instance; |
| 18 | } |
| 19 | |
| 20 | set<T>(key: string, data: T, ttl: number = 5 * 60 * 1000): void { |
| 21 | this.cache.set(key, { |
| 22 | data, |
| 23 | timestamp: Date.now(), |
| 24 | ttl |
| 25 | }); |
| 26 | } |
| 27 | |
| 28 | get<T>(key: string): T | null { |
| 29 | const item = this.cache.get(key); |
| 30 | if (!item) { |
| 31 | return null; |
| 32 | } |
| 33 | |
| 34 | const now = Date.now(); |
| 35 | if (now - item.timestamp > item.ttl) { |
| 36 | this.cache.delete(key); |
| 37 | return null; |
| 38 | } |
| 39 | |
| 40 | return item.data as T; |
| 41 | } |
| 42 | |
| 43 | delete(key: string): void { |
| 44 | this.cache.delete(key); |
| 45 | } |
| 46 | |
| 47 | clear(): void { |
| 48 | this.cache.clear(); |
| 49 | } |
| 50 | |
| 51 | // 清理过期的缓存项 |
| 52 | cleanup(): void { |
| 53 | const now = Date.now(); |
| 54 | Array.from(this.cache.entries()).forEach(([key, item]) => { |
| 55 | if (now - item.timestamp > item.ttl) { |
| 56 | this.cache.delete(key); |
| 57 | } |
| 58 | }); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | export const cache = Cache.getInstance(); |
| 63 |
nothing calls this directly
no outgoing calls
no test coverage detected