index.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { CacheData, Theme } from './type'
  2. /**
  3. * 全局缓存初始数据
  4. */
  5. const initData: CacheData = {
  6. loginInfo: {
  7. expiresAt: 0,
  8. token: '',
  9. user: {
  10. userName: '访客'
  11. },
  12. },
  13. theme: Theme.default,
  14. }
  15. /**
  16. * 本地存储类
  17. */
  18. function useStorage() {
  19. const getItem = <Key extends keyof CacheData>(key: Key): CacheData[Key] => {
  20. const str = wx.getStorageSync(key);
  21. if (str) {
  22. const value = JSON.parse(str);
  23. return value;
  24. } else {
  25. return initData[key];
  26. }
  27. }
  28. const setItem = <Key extends keyof CacheData>(key: Key, value: CacheData[Key]): void => {
  29. if (value !== undefined && value !== null) {
  30. const str = JSON.stringify(value);
  31. wx.setStorageSync(key, str);
  32. }
  33. }
  34. const removeItem = <Key extends keyof CacheData>(key: Key): void => {
  35. wx.removeStorageSync(key);
  36. }
  37. const clear = (): void => {
  38. wx.clearStorageSync();
  39. }
  40. return {
  41. get value() {
  42. const data = initData;
  43. type t = keyof CacheData;
  44. for (const key in data) {
  45. const k = key as t;
  46. (<CacheData[t]>data[k]) = getItem(k);
  47. }
  48. return data;
  49. },
  50. getItem,
  51. setItem,
  52. removeItem,
  53. clear
  54. }
  55. }
  56. export const globalCache = useStorage();