forked from Kong/swrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.ts
44 lines (37 loc) · 860 Bytes
/
cache.ts
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
interface ICacheItem {
data: any,
createdAt: number,
expiresAt: number
}
export default class SWRVCache {
private ttl: number
private items: Map<string, ICacheItem>
constructor (ttl = 0) {
this.items = new Map()
this.ttl = ttl
}
/**
* Get cache item while evicting
*/
get (k: string): ICacheItem {
return this.items.get(k)
}
set (k: string, v: any, ttl: number) {
const timeToLive = ttl || this.ttl
const now = Date.now()
const item = {
data: v,
createdAt: now,
expiresAt: timeToLive ? now + timeToLive : Infinity
}
timeToLive && setTimeout(() => {
const current = Date.now()
const hasExpired = current >= item.expiresAt
if (hasExpired) this.delete(k)
}, timeToLive)
this.items.set(k, item)
}
delete (k: string) {
this.items.delete(k)
}
}