import { CacheData, Theme } from './type' /** * 全局缓存初始数据 */ const initData: CacheData = { loginInfo: { expiresAt: 0, token: '', user: { userName: '访客' }, }, theme: Theme.default, } /** * 本地存储类 */ function useStorage() { const getItem = (key: Key): CacheData[Key] => { const str = wx.getStorageSync(key); if (str) { const value = JSON.parse(str); return value; } else { return initData[key]; } } const setItem = (key: Key, value: CacheData[Key]): void => { if (value !== undefined && value !== null) { const str = JSON.stringify(value); wx.setStorageSync(key, str); } } const removeItem = (key: Key): void => { wx.removeStorageSync(key); } const clear = (): void => { wx.clearStorageSync(); } return { get value() { const data = initData; type t = keyof CacheData; for (const key in data) { const k = key as t; (data[k]) = getItem(k); } return data; }, getItem, setItem, removeItem, clear } } export const globalCache = useStorage();