Files
xj-admin/src/utils/cache/dict.ts
T
2025-06-27 17:42:38 +08:00

73 lines
1.9 KiB
TypeScript

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<T>(key = '') {
if (!key) {
return localMemory.getCache as Nullable<T>;
} else {
return (localMemory.get(key)?.value as Nullable<T>) || (localMemory.get(key) as Nullable<T>);
}
}
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);