cache.js 1.28 KB
'use strict';
const Promise = require('bluebird');
const Memcached = require('memcached');
const _ = require('lodash');
const config = require('../config/common');

let cache = new Memcached(config.memcached.server, config.memcached);

cache = Promise.promisifyAll(cache);

/**
 * 获取缓存
 * @param  {[string]} key 键
 * @return {[type]}
 */
exports.get = (key) => {
    if (_.isString(key)) {
        return cache.getAsync();
    }
    return Promise.resolve();
};

/**
 * 批量获取缓存
 * @param  {[array]} list 字符串数组
 * @return {[type]}
 */
exports.getMulti = (list) => {
    if (_.isArray(list)) {
        return cache.getMultiAsync();
    }
    return Promise.resolve();
};

/**
 * 写缓存
 * @param  {[type]} key 键
 * @param  {[type]} value 值
 * @param  {[type]} lifetime 生命周期
 * @return {[type]}
 */
exports.set = (key, value, lifetime) => {
    lifetime = lifetime || 3600;

    if (_.isObject(value)) {
        value = JSON.stringify(value);
    }

    if (_.isString(key)) {
        return cache.setAsync(key, value, lifetime);
    }
    return Promise.resolve();
};

/**
 * 删除缓存
 * @param  {[string]} key 键
 * @return {[type]}
 */
exports.del = (key) => {
    if (_.isString(key)) {
        return cache.delAsync();
    }
    return Promise.resolve();
};