# all files / lib/Caches/ BasicJSCache.js

92.31% Statements 12/13
75% Branches 6/8
100% Functions 5/5
92.31% Lines 12/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

    5×

    4×
    3×
    1×
    1×

    2×

    1×

    3×

    3×

    1×

    1×

    1×
     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 (Itypeof cb === 'function') {
                cb(null, 'OK')
            }
        }
    }

    export default BasicJSCache