前言
使用cookie
是可以设置有效期的,但localStorage
本身是没有该机制的,只能手动删除,否则会一直存放在浏览器当中,我们可以把localStorage跟cookie一样设置一个有效期进行二次封装实现该方案。
在存储的时候设置一个过期时间,并且存储的数据进行格式化方便统一校验,在读取的时候获取当前时间进行判断是否过期,如果过期进行删除即可。
实现
1 2 3 4 5 6
|
export enum Dictionaries { expire = '__expire__', permanent = 'permanent' }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
import { Dictionaries } from "../enum"; export type Str=string; export type Expire = Dictionaries.permanent | number export interface Date<T>{ value:T, [Dictionaries.expire]:Expire }
export interface Result<T> { message: string, value: T | null }
export interface StorageCls { get: <T>(key:Str) => Result<T | null>; set: <T>(key:Str,value:T,expire:Expire) => void; remove: (key: Str) => void; clear: () => void; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
import { StorageCls, Str, Expire, Date, Result } from "./type"; import { Dictionaries } from "./enum"; export class Storage implements StorageCls { public get<T = any>(key: Str): Result<T | null> { const value = localStorage.getItem(key) if (value) { const data: Date<T> = JSON.parse(value); const now = new Date().getTime(); if (typeof data[Dictionaries.expire] == 'number' && data[Dictionaries.expire] < now) { this.remove(key) return { message: `您的${key}已过期`, value: null } } else { return { message: "成功读取", value: data.value } } } return { message: '值无效', value: null } } set<T = any>(key: Str, value: T, expire: Expire = Dictionaries.permanent) { const data: Date<T> = { value, [Dictionaries.expire]: expire } localStorage.setItem(key, JSON.stringify(data));
} remove(key: Str) { localStorage.removeItem(key); } clear() { localStorage.clear() } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import path from 'path' import ts from 'rollup-plugin-typescript2' import { terser } from 'rollup-plugin-terser' import server from 'rollup-plugin-serve' import livereload from 'rollup-plugin-livereload' import replace from 'rollup-plugin-replace' import { fileURLToPath } from 'url' const __filenameNew = fileURLToPath(import.meta.url) const __dirnameNew = path.dirname(__filenameNew) const isDev = () => { return process.env.NODE_ENV === 'development' } export default { input: './src/index.ts', output: { file: path.resolve(__dirnameNew, './lib/index.js'), sourcemap: true, }, plugins: [ ts(), isDev() && livereload(), terser({ compress: { drop_console: !isDev(), } }), replace({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), isDev() && server({ open: true, port: 1988, openPage: '/public/index.html', }),
]
}
|