1
|
'use strict'
|
2
|
|
3
|
const LRU = require('lru-cache')
|
4
|
|
5
|
const MAX_SIZE = 50 * 1024 * 1024 // 50MB
|
6
|
const MAX_AGE = 3 * 60 * 1000
|
7
|
|
8
|
let MEMOIZED = new LRU({
|
9
|
max: MAX_SIZE,
|
10
|
maxAge: MAX_AGE,
|
11
|
length: (entry, key) => {
|
12
|
if (key.startsWith('key:')) {
|
13
|
return entry.data.length
|
14
|
} else if (key.startsWith('digest:')) {
|
15
|
return entry.length
|
16
|
}
|
17
|
}
|
18
|
})
|
19
|
|
20
|
module.exports.clearMemoized = clearMemoized
|
21
|
function clearMemoized () {
|
22
|
const old = {}
|
23
|
MEMOIZED.forEach((v, k) => {
|
24
|
old[k] = v
|
25
|
})
|
26
|
MEMOIZED.reset()
|
27
|
return old
|
28
|
}
|
29
|
|
30
|
module.exports.put = put
|
31
|
function put (cache, entry, data, opts) {
|
32
|
pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data })
|
33
|
putDigest(cache, entry.integrity, data, opts)
|
34
|
}
|
35
|
|
36
|
module.exports.put.byDigest = putDigest
|
37
|
function putDigest (cache, integrity, data, opts) {
|
38
|
pickMem(opts).set(`digest:${cache}:${integrity}`, data)
|
39
|
}
|
40
|
|
41
|
module.exports.get = get
|
42
|
function get (cache, key, opts) {
|
43
|
return pickMem(opts).get(`key:${cache}:${key}`)
|
44
|
}
|
45
|
|
46
|
module.exports.get.byDigest = getDigest
|
47
|
function getDigest (cache, integrity, opts) {
|
48
|
return pickMem(opts).get(`digest:${cache}:${integrity}`)
|
49
|
}
|
50
|
|
51
|
class ObjProxy {
|
52
|
constructor (obj) {
|
53
|
this.obj = obj
|
54
|
}
|
55
|
get (key) { return this.obj[key] }
|
56
|
set (key, val) { this.obj[key] = val }
|
57
|
}
|
58
|
|
59
|
function pickMem (opts) {
|
60
|
if (!opts || !opts.memoize) {
|
61
|
return MEMOIZED
|
62
|
} else if (opts.memoize.get && opts.memoize.set) {
|
63
|
return opts.memoize
|
64
|
} else if (typeof opts.memoize === 'object') {
|
65
|
return new ObjProxy(opts.memoize)
|
66
|
} else {
|
67
|
return MEMOIZED
|
68
|
}
|
69
|
}
|