| const TWO_HOURS_MS = 2 * 60 * 60 * 1000 |
| const DEFAULT_MAX = 1000 |
|
|
| class CacheStore { |
| constructor({ ttl = TWO_HOURS_MS, max = DEFAULT_MAX } = {}) { |
| this.ttl = ttl |
| this.max = max |
| this.store = new Map() |
| } |
|
|
| get(key) { |
| const entry = this.store.get(key) |
| if (!entry) return null |
|
|
| if (Date.now() > entry.expires) { |
| this.store.delete(key) |
| return null |
| } |
|
|
| return entry.value |
| } |
|
|
| set(key, value) { |
| if (this.store.size >= this.max) { |
| const oldestKey = this.store.keys().next().value |
| if (oldestKey !== undefined) { |
| this.store.delete(oldestKey) |
| } |
| } |
|
|
| this.store.set(key, { |
| value, |
| expires: Date.now() + this.ttl, |
| }) |
| } |
|
|
| delete(key) { |
| return this.store.delete(key) |
| } |
|
|
| clear() { |
| this.store.clear() |
| } |
| } |
|
|
| const linkCache = new CacheStore() |
|
|
| function cacheLink(id, link) { |
| if (!id || typeof id !== 'string') { |
| console.error('ID inválido:', id) |
| return false |
| } |
|
|
| linkCache.set(id, { result: link }) |
| console.log(`Enlace cacheado para ID ${id}:`, link) |
| return true |
| } |
|
|
| function getCachedLink(id) { |
| return linkCache.get(id) |
| } |
|
|
| module.exports = { |
| CacheStore, |
| cacheLink, |
| getCachedLink, |
| linkCache, |
| } |
|
|