| 1 | /** Keyed in-memory cache with TTL and max entry limit. */ |
| 2 | export class ApiCache<T> { |
| 3 | private cache = new Map<string, { data: T; fetchedAt: number }>(); |
| 4 | |
| 5 | constructor( |
| 6 | private ttl: number, |
| 7 | private maxEntries = 200 |
| 8 | ) {} |
| 9 | |
| 10 | get(key: string): T | null { |
| 11 | const entry = this.cache.get(key); |
| 12 | if (!entry) return null; |
| 13 | if (Date.now() - entry.fetchedAt > this.ttl) { |
| 14 | this.cache.delete(key); |
| 15 | return null; |
| 16 | } |
| 17 | return entry.data; |
| 18 | } |
| 19 | |
| 20 | set(key: string, data: T): void { |
| 21 | this.cache.set(key, { data, fetchedAt: Date.now() }); |
| 22 | if (this.cache.size > this.maxEntries) { |
| 23 | const now = Date.now(); |
| 24 | for (const [k, v] of this.cache) { |
| 25 | if (now - v.fetchedAt > this.ttl) this.cache.delete(k); |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /** Single-value in-memory cache with TTL. */ |
| 32 | export class SingleCache<T> { |
nothing calls this directly
no outgoing calls
no test coverage detected