| | |
| | | /* eslint-disable @typescript-eslint/no-explicit-any */ |
| | | import Taro from '@tarojs/taro'; |
| | | interface ProxyStorage { |
| | | getItem(key: string): any; |
| | | setItem(Key: string, value: string): void; |
| | | removeItem(key: string): void; |
| | | clear(): void; |
| | | } |
| | | |
| | | //sessionStorage operate |
| | | class localStorageProxy { |
| | | constructor() {} |
| | | class sessionStorageProxy implements ProxyStorage { |
| | | protected storage: ProxyStorage; |
| | | |
| | | constructor(storageModel: ProxyStorage) { |
| | | this.storage = storageModel; |
| | | } |
| | | |
| | | // 存 |
| | | public setItem(key: string, value: any): void { |
| | | return Taro.setStorageSync(key, JSON.stringify(value)); |
| | | this.storage.setItem(key, JSON.stringify(value)); |
| | | } |
| | | |
| | | // 取 |
| | | public getItem<T = any>(key: string): Nullable<T> { |
| | | try { |
| | | const value = Taro.getStorageSync(key); |
| | | if (value) { |
| | | // Do something with return value |
| | | return JSON.parse(value); |
| | | } |
| | | return null; |
| | | } catch (e) { |
| | | // Do something when catch error |
| | | return null; |
| | | } |
| | | public getItem<T = any>(key: string): null | T { |
| | | return JSON.parse(this.storage.getItem(key)); |
| | | } |
| | | |
| | | // 删 |
| | | public removeItem(key: string) { |
| | | return Taro.removeStorageSync(key); |
| | | public removeItem(key: string): void { |
| | | this.storage.removeItem(key); |
| | | } |
| | | |
| | | // 清空 |
| | | public clear() { |
| | | return Taro.clearStorage(); |
| | | public clear(): void { |
| | | this.storage.clear(); |
| | | } |
| | | } |
| | | |
| | | export const storageLocal = new localStorageProxy(); |
| | | //localStorage operate |
| | | class localStorageProxy extends sessionStorageProxy implements ProxyStorage { |
| | | constructor(localStorage: ProxyStorage) { |
| | | super(localStorage); |
| | | } |
| | | } |
| | | |
| | | export const storageSession = new sessionStorageProxy(sessionStorage); |
| | | |
| | | export const storageLocal = new localStorageProxy(localStorage); |