import { createLocalStorage } from '/@/utils/cache'; import { Memory } from './memory'; import { DB_DICT_DATA_KEY } from '/@/enums/cacheEnum'; import { DEFAULT_CACHE_TIME } from '/@/settings/encryptionSetting'; import { toRaw } from 'vue'; import { useUserStoreWithOut } from '/@/store/modules/user'; const ls = createLocalStorage({ hasEncrypt: false }); const localMemory = new Memory(DEFAULT_CACHE_TIME); export function initDictMemory() { const localCache = ls.get(DB_DICT_DATA_KEY); localCache && localMemory.resetCache(localCache); localCache && initStore(localCache); } function initStore(cache: any) { const userStore = useUserStoreWithOut(); const { setAllDictItems } = userStore; setAllDictItems(cache); } export class Dict { static getDict(key = '') { if (!key) { return localMemory.getCache as Nullable; } else { return (localMemory.get(key)?.value as Nullable) || (localMemory.get(key) as Nullable); } } static setDict(key, value: object, immediate = false): void { if (!key) { localMemory.setCache(value); } else { localMemory.set(key, toRaw(value)); } immediate && ls.set(DB_DICT_DATA_KEY, localMemory.getCache); } static store() { ls.set(DB_DICT_DATA_KEY, localMemory.getCache); } static removeDict(key, immediate = false): void { localMemory.remove(key); immediate && ls.set(DB_DICT_DATA_KEY, localMemory.getCache); } static clearDict(immediate = false): void { localMemory.clear(); immediate && ls.remove(DB_DICT_DATA_KEY); } } function storageChange(e: any) { const { key, newValue, oldValue } = e; if (!key) { Dict.clearDict(); return; } if (!!newValue && !!oldValue) { if (DB_DICT_DATA_KEY === key) { Dict.clearDict(); } } } window.addEventListener('storage', storageChange);