-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlru.js
55 lines (41 loc) · 1.1 KB
/
lru.js
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
'use strict'
const LRU = require('lru-cache')
const {isNil} = require('lodash')
const { ONE_HOUR, LISTEN_TTL, PENDING, TEN_THOUSAND } = require('./constant')
const init = (options) => {
const lruOptions = {
length: (value) => JSON.stringify(value).length,
max: options.max || TEN_THOUSAND,
maxAge: options.maxAge || ONE_HOUR
}
const lru = LRU(lruOptions)
const store = {
get: (key) => lru.get(key),
set: (key, val) => lru.set(key, val),
reserve: (key) => {
const val = lru.get(key)
if (val === PENDING) {
return false
}
lru.set(key, PENDING)
return true
},
expire: (key) => lru.del(key),
listen: (key) => new Promise((resolve, reject) => {
const interval = setInterval(() => {
const data = lru.get(key)
if (isNil(data)) {
clearInterval(interval)
return resolve(data)
}
if (data !== PENDING) {
clearInterval(interval)
return resolve(data)
}
}, LISTEN_TTL)
}),
reset: () => lru.reset()
}
return store
}
module.exports = { init }