| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import { CacheData, Theme } from './type'
- /**
- * 全局缓存初始数据
- */
- const initData: CacheData = {
- loginInfo: {
- expiresAt: 0,
- token: '',
- user: {
- userName: '访客'
- },
- },
- theme: Theme.default,
- }
- /**
- * 本地存储类
- */
- function useStorage() {
- const getItem = <Key extends keyof CacheData>(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 extends keyof CacheData>(key: Key, value: CacheData[Key]): void => {
- if (value !== undefined && value !== null) {
- const str = JSON.stringify(value);
- wx.setStorageSync(key, str);
- }
- }
- const removeItem = <Key extends keyof CacheData>(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;
- (<CacheData[t]>data[k]) = getItem(k);
- }
- return data;
- },
- getItem,
- setItem,
- removeItem,
- clear
- }
- }
- export const globalCache = useStorage();
|