'custome defined'
const redis = require('redis');
const bluebird = require("bluebird");
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

module.exports = {
    init: function () {
        this.client = redis.createClient('6379', '127.0.0.1');
        this.client.flushdb(function (err, succeeded) {
            console.log(succeeded); // will be true if successfull
        });
    },
    set: function (ctx, key, value, time_out = 30000) {
        var val = JSON.stringify({ type: typeof value, val: value });
        this.client.set(`${ctx.request.ip}${key}`, val);
        this.client.expire(`${ctx.request.ip}${key}`, time_out);//设定失效时间,没有生效
    },
    del: async function (ctx, key) {
        return this.client.del(`${ctx.request.ip}${key}`)
    },
    get: function (ctx, key) {
        return   this.client.getAsync(`${ctx.request.ip}${key}`).then(function(records){
            try {
                if (!!!records){
                    return null
                }else{
                    return JSON.parse(records).val   
                }
            } catch (error) {
                return error
            }
        });
    }
}