缓存
# storage
storage.js
一个通用存储类,支持过期时间设置,storage默认为localStorage可切换为sessionStorage;顺带cookie设置;
// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7
// 给本应用的Storage每一个键名前加一个前缀
const PREFIX_KEY = 'APP-NAME'
/**
* 创建本地缓存对象
* @param {Object} opt - 非必传
* @param {string} opt.prefixKey - 自定义前缀(默认取 PREFIX_KEY)
* @param {string} opt.storage - 储存引擎 sessionStorage | localStorage(默认)
*/
export const createStorage = (opt={}) => {
let prefixKey = opt.prefixKey || PREFIX_KEY
let storage = opt.storage || localStorage
/**
* 本地缓存类
* @class Storage
*/
const Storage = class {
constructor(storage, prefixKey) {
this.storage = storage
this.prefixKey = prefixKey
}
/**
* @description key加前缀
* @param {string} key 缓存键
*/
getKey(key) {
return `${this.prefixKey}${key}`.toUpperCase()
}
/**
* @description 设置缓存
* @param {string} key 缓存键
* @param {*} value 缓存值
* @param {number | null} expire
*/
set(key, value, expire = DEFAULT_CACHE_TIME) {
const stringData = JSON.stringify({
value,
expire: expire !== null ? new Date().getTime() + expire * 1000 : null
})
this.storage.setItem(this.getKey(key), stringData)
}
/**
* 读取缓存
* @param {string} key 缓存键
* @param {*=} def 默认值
*/
get(key, def = null) {
const item = this.storage.getItem(this.getKey(key))
if (item) {
try {
const data = JSON.parse(item)
const { value, expire } = data
// 在有效期内直接返回
if (expire === null || expire >= Date.now()) {
return value
}
this.remove(this.getKey(key))
} catch (e) {
return def
}
}
return def
}
/**
* 从缓存删除某项
* @param {string} key
*/
remove(key) {
this.storage.removeItem(this.getKey(key))
}
/**
* 清空所有缓存
* @memberOf Cache
*/
clear() {
this.storage.clear()
}
/**
* 设置cookie
* @param {string} name cookie 名称
* @param {*} value cookie 值
* @param {number=} expire 过期时间
* 如果过期时间为设置,默认关闭浏览器自动删除
* @example
*/
setCookie(name, value, expire = DEFAULT_CACHE_TIME) {
document.cookie = `${this.getKey(name)}=${value}; Max-Age=${expire}`
}
/**
* 根据名字获取cookie值
* @param name
*/
getCookie(name) {
const cookieArr = document.cookie.split('; ')
for (let i = 0, length = cookieArr.length; i < length; i++) {
const kv = cookieArr[i].split('=')
if (kv[0] === this.getKey(name)) {
return kv[1]
}
}
return ''
}
/**
* 根据名字删除指定的cookie
* @param {string} key
*/
removeCookie(key) {
this.setCookie(key, 1, -1)
}
/**
* 清空cookie,使所有cookie失效
*/
clearCookie() {
const keys = document.cookie.match(/[^ =;]+(?==)/g)
if (keys) {
for (let i = keys.length; i--; ) {
document.cookie = keys[i] + '=0;expire=' + new Date(0).toUTCString()
}
}
}
}
return new Storage(storage, prefixKey)
}
export const Storage = createStorage()
export default Storage
// eg:
Storage().set('token2', '123456789', null) // 不过期
console.log( Storage().get('token2') ); // 123456789
Storage().set('token', '123456789', 1) // 1秒后过期
setTimeout(() => {
console.log( Storage().get('token') ); // null
}, 1200);
Storage().setCookie('uid', '100011', 60 * 60 * 24 * 1) // 1天后过期
console.log( Storage().getCookie('uid') );
# 获取所有 cookie 并转为对象
const getCookies = () => document.cookie
.split(';')
.map(item => item.split('='))
.reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] =v) && acc, {})
# 清除所有 cookie
const clearCookies = () => document.cookie
.split(';')
.forEach(c => document.cookie = c.splace(/^+/, '')
.replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`))
)
上次更新: 2022/08/24, 16:19:12