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

前言

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

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

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

核心实现

javascript 复制代码
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.灵活的存储方式

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

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

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

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

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

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

相关推荐
海尔辛6 分钟前
学习黑客 shell 脚本
前端·chrome·学习
每天吃饭的羊13 分钟前
XSS ..
前端
2301_7891695439 分钟前
ai说什么是注解,并以angular ts为例
javascript
小李李31 小时前
基于Node.js的Web爬虫: 使用Axios和Cheerio抓取网页数据
前端·爬虫·node.js·跨域
酷小洋1 小时前
CSS基础
前端·css
xinruoqianqiu1 小时前
shell脚本--2
linux·运维·开发语言·前端·c++·chrome
几度泥的菜花2 小时前
Vue 项目中长按保存图片功能实现指南
前端·javascript·vue.js
学习机器不会机器学习2 小时前
什么是跨域,如何解决跨域问题
前端·后端
Code哈哈笑2 小时前
【图书管理系统】详细讲解用户登录:后端代码实现及讲解、前端代码讲解
前端·spring boot·后端·spring·状态模式
前端小崔2 小时前
从零开始学习three.js(14):一文详解three.js中的粒子系统Points
开发语言·前端·javascript·学习·3d·webgl·数据可视化