每日前端小技巧 - 客户端缓存封装

275 阅读1分钟

前言

在前端开发中,我们经常需要使用 localStorage 或 sessionStorage 来存储数据。但原生的 Storage API 存在一些使用上的不便:

  • 只能存储字符串
  • 没有过期时间机制
  • 错误处理不够优雅
  • 前缀管理不便

今天分享一个客户端缓存封装方案,来解决以上问题。

核心实现

class Storage {
    constructor(prefix,storage){
        this.storage = storage ?? localStorage;
        this.prefix = prefix ?? 'cache_';
    }

    getKey = (key) => {
        return `${this.prefix}${key}`;
    }

    /**
     * 写入
     * @param key
     * @param value
     * @param validTime 有效时间,单位 s
     */
    set = (key, value, validTime)=> {
        if (value === null || value === undefined) {
            this.del(key);
            return;
        }
        this.storage.setItem(
            this.getKey(key),
            JSON.stringify({
                value,
                validTime: validTime ? validTime * 1000 : undefined,
                writeTime: Date.now()
            })
        );
    }
    get = (key)=> {
        const result =  this.storage.getItem(this.getKey(key))
        if (result === null || result === undefined || result === '') {
            return null;
        }
        try {
            const { value, validTime, writeTime } = JSON.parse(result);
            if (validTime) {
                if (Date.now() - writeTime > validTime) {
                    // 已过期
                    this.del(key);
                    return null;
                }
            }
            return value;
        } catch (err) {
            console.error(`获取 ${key} 失败`, err);
            // 清除掉不合法数据,防止持续报错
            this.del(key);
            return null;
        }
    }
    del = (key)=> {
        this.storage.removeItem(this.getKey(key));
    }

    clear = ()=> {
        const keys = Object.keys(this.storage);
        keys.forEach(key => {
            if (key.startsWith(this.prefix)) {
                this.storage.removeItem(key);
            }
        });
    }
}

特性介绍

1.灵活的存储方式

// 支持 localStorage 和 sessionStorage
const localStore = new Storage('app_', localStorage);
const sessionStore = new Storage('app_', sessionStorage);
  1. 支持数据过期
// 设置 60 秒后过期
localStore.set('userInfo', { name: 'John' }, 60);

// 过期后自动返回 null
setTimeout(() => {
    console.log(localStore.get('userInfo')); // null
}, 61000);

3.自动序列化/反序列化

// 支持存储对象
localStore.set('config', {
    theme: 'dark',
    language: 'zh-CN'
});

// 直接获取对象
const config = localStore.get('config');
console.log(config.theme); // 'dark'
  1. 错误处理
// 错误处理
// 存储非法数据时自动清除
localStorage.setItem('test', '{invalid json}');
const value = localStore.get('test'); // null,并自动清除错误数据
  1. 前缀管理
// 统一前缀管理
const localStore = new Storage('app_', localStorage);
localStore.set('userInfo', { name: 'John' });
localStore.set('config', { theme: 'dark' });
// 清除所有 app_ 开头的键值对
localStore.clear();

通过这个封装方案,我们可以更优雅地管理客户端缓存数据。如果觉得文章有帮助,欢迎点赞转发