/**
 * /cache/_redis.js
 * redis的方法get和set
*/

const redis = require('redis');

const config = require(`../config/config.default.js`).config;

const REDIS_CONF = config.redis;


class RedisService {
    constructor() {
        // 创建客户端
        const redisClient = redis.createClient({
            url: `redis://${REDIS_CONF.host}:${REDIS_CONF.port}/0`,
            password: REDIS_CONF.password
        })
        redisClient.connect();
        this.redisClient = redisClient;
    };

    /**
 * redis set
 * @param {string} key 键
 * @param {string} val 值
 * @param {number} timeout 过期时间，单位 s
 */
    async set(key, val, timeout = 60 * 60) {
        if (typeof val === 'object') {
            val = JSON.stringify(val)
        }
        await this.redisClient.set(key, val)
        await this.redisClient.expire(key, timeout)
    }

    /**
     * redis get
     * @param {string} key 键
     */
    async get(key) {
        const val = await this.redisClient.get(key);
        return val;
    }

        /**
     * redis del
     * @param {string} key 键
     */
        async del(key) {
            const val = await this.redisClient.del(key);
            return val;
        }

}

/**signleton */
exports.RedisService = new RedisService();
