cache-utils.js 1.19 KB
const cache = global.yoho.cache;
const logger = global.yoho.logger;

const ONE_MINUTE = 60;
const FIVE_MINUTE = 5 * ONE_MINUTE;

function _cacheGet(key) {
    return cache.get(key).then((data) => {
        if (data) {
            return JSON.parse(data);
        }

        return Promise.reject();
    });
}

function _cacheSave(key, value, ttl) {
    return cache.set(key, value, ttl)
        .catch(err => logger.error(`save cache data fail:${err.toString()}`));
}

function defaultKey() {
    const args = Array.prototype.slice.call(arguments);

    return JSON.stringify(args || '[]');
}

function _cached(fn, keyFn = defaultKey, ctx = null, ttl = FIVE_MINUTE) {
    const keyGen = function() {
        const args = Array.prototype.slice.call(arguments);

        return '_cache:' + (fn.name || '') + ':' + keyFn.apply(null, args);
    };

    return function() {
        const args = Array.prototype.slice.call(arguments);
        const key = keyGen.apply(null, args);

        return _cacheGet(key).catch(() => {
            return fn.apply(ctx, args).then(result => {
                _cacheSave(key, result, ttl);
                return result;
            });
        });
    };
}

module.exports = _cached;