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