all files / lib/Caches/ RedisCache.js

18.18% Statements 2/11
0% Branches 0/4
0% Functions 0/5
18.18% Lines 2/11
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 40 41 42 43 44 45 46 47                                                                                          
import redis from 'redis'
 
// The set/get are pretty inefficient, but this will do for now.
 
class RedisCache {
    constructor(opts) {
        const options = Object.assign(
            {
                host: '127.0.0.1',
                port: 6379,
                keyPrefix: 'kayn-',
            },
            opts || {},
        )
 
        this.client = redis.createClient(options)
 
        // Should probably remove this...
        this.client.on('error', function(err) {
            console.log('Redis error:', err)
        })
 
        this.prefix = options.keyPrefix
    }
 
    get(args, cb) {
        this.client.get(this.prefix + args.key, (err, reply) => {
            reply ? cb(err, JSON.parse(reply)) : cb(err)
            return
        })
    }
 
    set(args, value) {
        this.client.setex(
            this.prefix + args.key,
            args.ttl,
            JSON.stringify(value),
        )
    }
 
    flushCache(cb) {
        this.client.flushdb(cb)
    }
}
 
export default RedisCache