封装storage存储class
export enum StorageType {
session = 'session',
local = 'local'
}
export class MyStorage {
private prefix: string
private static _instance: Map<string, MyStorage>
private storage: Storage
private engine = {
[StorageType.session]: sessionStorage,
[StorageType.local]: localStorage
}
constructor(prefix = '', type: StorageType = StorageType.local) {
this.prefix = prefix
this.storage = this.engine[type]
if (!this.storage) {
throw new Error("engine type error. it must be 'session','local'")
}
if (!MyStorage._instance) {
MyStorage._instance = new Map()
}
if (!MyStorage._instance?.has(type)) {
MyStorage._instance.set(type, this)
}
return MyStorage._instance.get(type) as MyStorage
}
private getFullKey(value: string) {
return this.prefix + value
}
set(key: string, value: any, expire = 0) {
try {
const wrapData = {
value,
expire,
time: Date.now()