js的缓存工具
项目中用到的一个localStorage工具,可以用于token存储、数据缓存,支持过期,使用起来简答快捷
JavaScript版
const DEFAULT_EXPIRE = 7200; // 默认存储时间(秒)
const cache = {
    /**
     * 设置缓存
     * @param {string} key 存储的键
     * @param {any} value 存储的值
     * @param {number} [expire=DEFAULT_EXPIRE] 过期时间(秒),默认 7200s
     */
    set: (key, value, expire = DEFAULT_EXPIRE) => {
        const expireTimestamp = Date.now() + expire * 1000;
        const cacheData = { data: value, expireTimestamp };
        localStorage.setItem(key, JSON.stringify(cacheData));
    },
    /**
     * 获取缓存
     * @param {string} key 存储的键
     * @param {any} [defaultValue=null] 如果缓存不存在,返回的默认值
     * @returns {any|null} 获取到的数据,或者默认值
     */
    get: (key, defaultValue = null) => {
        const item = localStorage.getItem(key);
        if (!item) return defaultValue;
        try {
            const cacheData = JSON.parse(item);
            if (Date.now() > cacheData.expireTimestamp) {
                cache.remove(key); // 过期后删除
                return defaultValue;
            }
            return cacheData.data;
        } catch (error) {
            console.error("解析缓存数据失败:", error);
            cache.remove(key);
            return defaultValue;
        }
    },
    /**
     * 删除缓存
     * @param {string} key 存储的键
     */
    remove: (key) => {
        localStorage.removeItem(key);
    },
    /**
     * 清空所有缓存
     */
    clear: () => {
        localStorage.clear();
    }
};
export default cache;typeScript版
const DEFAULT_EXPIRE = 7200; // 默认存储时间(秒)
interface CacheData<T> {
    data: T;
    expireTimestamp: number;
}
const cache = {
    /**
     * 设置缓存
     * @param key 存储的键
     * @param value 存储的值
     * @param expire 过期时间(秒),默认 7200s
     */
    set: <T>(key: string, value: T, expire: number = DEFAULT_EXPIRE) => {
        const expireTimestamp = Date.now() + expire * 1000;
        const cacheData: CacheData<T> = { data: value, expireTimestamp };
        localStorage.setItem(key, JSON.stringify(cacheData));
    },
    /**
     * 获取缓存
     * @param key 存储的键
     * @param defaultValue 如果缓存不存在,返回的默认值
     * @returns T | null
     */
    get: <T>(key: string, defaultValue: T | null = null): T | null => {
        const item = localStorage.getItem(key);
        if (!item) return defaultValue;
        try {
            const cacheData: CacheData<T> = JSON.parse(item);
            if (Date.now() > cacheData.expireTimestamp) {
                cache.remove(key); // 过期后删除
                return defaultValue;
            }
            return cacheData.data;
        } catch (error) {
            console.error("解析缓存数据失败:", error);
            cache.remove(key);
            return defaultValue;
        }
    },
    /**
     * 删除缓存
     * @param key 存储的键
     */
    remove: (key: string) => {
        localStorage.removeItem(key);
    },
    /**
     * 清空所有缓存
     */
    clear: () => {
        localStorage.clear();
    }
};
export default cache;