all files / Caches/ BasicJSCache.js

7.69% Statements 1/13
0% Branches 0/8
0% Functions 0/5
7.69% Lines 1/13
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                                                                           
class BasicJSCache {
    constructor() {
        this.cache = {}
    }
 
    get(args, cb) {
        if (this.cache[args.key]) {
            if (Date.now() > this.cache[args.key].expires) {
                delete this.cache[args.key]
                return cb('expired cache key', null)
            } else {
                return cb(null, this.cache[args.key].value)
            }
        }
        return cb("cache key doesn't exist", null)
    }
 
    set(args, value) {
        this.cache[args.key] = {
            expires: args.ttl ? this.setExp(Date.now(), args.ttl) : null,
            value: value,
        }
    }
 
    setExp(date, ms) {
        return date + ms
    }
 
    flushCache(cb) {
        this.cache = {}
        // Promise/await compatibility.
        if (typeof cb === 'function') {
            cb(null, 'OK')
        }
    }
}
 
export default BasicJSCache