cacheManager.js 2.38 KB
/**
 * Created by shipfi on 2016/10/8.
 */

var cacheType = {
    CA_MAIN_MENU: 'MAIN_MENU', /* 菜单数据 */
    CA_USER_INFO: 'USER_INFO', /* 个人信息数据 */
    CA_GROUP_INFO: 'GROUP_INFO', /* 集团配置信息 */
    CA_SHOP_ENTRY: 'SHPO_ENTRY', /* 商城入口地址 */
    CA_SHOP_ORDER_ENTRY: 'SHOP_ORDER_ENTRY', /* 商城订单入口地址 */
    CA_COLUMN_LIST: 'COLUMN_LIST', /* 社区栏目*/
    CA_INDEX_COLUMN_LIST: 'INDEX_COLUMN_LIST', /* 首页栏目列表 */
    CA_INDEX_TOPIC_LIST: 'INDEX_TOPIC_LIST', /* 首页帖子列表 */
    CA_BANNER_LIST: 'BANNER_LIST', /* 轮播广告列表 */
};

var cacheManager = {

    /**
     * 清除应用所有缓存
     */
    clearAll: function () {
        window.localStorage.clear();
    },

    clearItem: function (key) {
        window.localStorage.removeItem(key);
        return true;
    },

    /**
     * 获得缓存信息
     * @param key
     * @returns {*}
     */
    get: function (key) {

        var d = new Date();
        var currentTime = parseInt(d.getTime()); // millisecond 

        var storeData = window.localStorage.getItem(key);
        if (!storeData) {
            return false;
        }

        var storeDataFormat = JSON.parse(storeData);

        if (typeof storeDataFormat != 'object' || typeof storeDataFormat.expireTime != 'number') {
            return false;
        }

        console.log('====> Expire Time : ' + storeDataFormat.expireTime + '; CurrentTime : ' + currentTime);

        if (storeDataFormat.expireTime != 0 && storeDataFormat.expireTime <= currentTime) {
            window.localStorage.removeItem(key);
            return false;
        }

        return storeDataFormat.saveValue;
    },

    /**
     * 存储缓存数据
     * @param key
     * @param value
     * @param expires
     * @returns {boolean}
     */
    set: function (key, value, expires = 3600) {

        if (typeof value == 'undefined' || !value) {
            return false;
        }

        var d = new Date();
        var currentTime = parseInt(d.getTime());     // millisecond 
        var expireTime = (expires == 0) ? 0 : currentTime + (expires * 1000);
        var storeData = {
            saveTime: currentTime,
            saveValue: value,
            expireTime: expireTime
        };

        window.localStorage.setItem(key, JSON.stringify(storeData));

        return true;
    }
};

export {cacheType, cacheManager};