File size: 1,221 Bytes
92a83a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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,
}