memory-cache.js 1.82 KB
/**
 * memoryCache
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2018/07/23
 */

const _ = require('lodash');

module.exports = class memoryCache {
    constructor(options) {
        this.options = Object.assign({}, options);
        this.cache = {};
        this.map = [];

        this.options.maxLength = parseInt(this.options.maxLength, 10) || 1000;
    }
    _deleteCache(key) {
        delete this.cache[key];
    }
    _deleteMap(key) {
        _.remove(this.map, (n) => {
            return n === key;
        });
    }
    _getNowTime() {
        return new Date().getTime() / 1000;
    }

    // 获取缓存数据
    get(key) {
        if (!this.cache.hasOwnProperty(key)) {
            return;
        }

        let info = this.cache[key];

        // 校验过期时间
        if (info.exptime && info.exptime - this._getNowTime() < 0) {
            this.clear(key);
            return;
        }

        return _.cloneDeep(info.value);
    }

    // 设置缓存数据
    set(key, value, exptime) {
        this.cache.hasOwnProperty(key) && this._deleteMap(key);

        this.map.push(key);
        this.cache[key] = {
            value: _.cloneDeep(value),
            exptime: exptime ? (exptime + this._getNowTime()) : 0 // 过期时间
        };

        const maxLength = this.options.maxLength;

        // 清除老旧数据
        if (this.map.length > maxLength) {
            let len = this.map.length - maxLength;

            for (let i = 0; i < len; i++) {
                this._deleteCache(this.map.shift());
            }
        }
    }

    // 清除单条缓存数据
    clear(key) {
        if (this.cache.hasOwnProperty(key)) {
            this._deleteMap(key);
            this._deleteCache(key);
        }
    }

    // 清除所有缓存数据
    clearAll() {
        this.cache = {};
        this.map = [];
    }
};