1'use strict' 2 3const LRU = require('lru-cache') 4 5const MAX_SIZE = 50 * 1024 * 1024 // 50MB 6const MAX_AGE = 3 * 60 * 1000 7 8let 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 20module.exports.clearMemoized = clearMemoized 21function clearMemoized () { 22 const old = {} 23 MEMOIZED.forEach((v, k) => { 24 old[k] = v 25 }) 26 MEMOIZED.reset() 27 return old 28} 29 30module.exports.put = put 31function put (cache, entry, data, opts) { 32 pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) 33 putDigest(cache, entry.integrity, data, opts) 34} 35 36module.exports.put.byDigest = putDigest 37function putDigest (cache, integrity, data, opts) { 38 pickMem(opts).set(`digest:${cache}:${integrity}`, data) 39} 40 41module.exports.get = get 42function get (cache, key, opts) { 43 return pickMem(opts).get(`key:${cache}:${key}`) 44} 45 46module.exports.get.byDigest = getDigest 47function getDigest (cache, integrity, opts) { 48 return pickMem(opts).get(`digest:${cache}:${integrity}`) 49} 50 51class 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 59function 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} 70