Files
iot-device-management-frontend/packages/preference/src/cache.ts

60 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-05-19 21:20:42 +08:00
import type { Preference } from '@vben-core/typings';
class PreferenceCache {
cachePrefix: string;
2024-05-24 23:11:03 +08:00
constructor(cachePrefix: string) {
2024-05-19 21:20:42 +08:00
this.cachePrefix = cachePrefix;
}
/**
* localStorage
* @returns localStorage
*/
get(defaultValue: Preference): Preference {
let cache = defaultValue;
try {
cache = JSON.parse(localStorage.getItem(this.getCacheKey()) || '');
} catch {
return defaultValue;
}
return cache;
}
/**
*
*/
getCacheKey(name: string = 'preference') {
2024-05-24 23:11:03 +08:00
return `__${this.cachePrefix}-${name}__`;
2024-05-19 21:20:42 +08:00
}
/**
* localStorage
*/
remove() {
localStorage.removeItem(this.getCacheKey());
localStorage.removeItem(this.getCacheKey('locale'));
localStorage.removeItem(this.getCacheKey('theme'));
}
/**
* localStorage
*/
set(preference: Preference) {
localStorage.setItem(this.getCacheKey(), JSON.stringify(preference));
// 额外存储一份主题、语言
localStorage.setItem(this.getCacheKey('locale'), preference.locale);
localStorage.setItem(this.getCacheKey('theme'), preference.theme);
}
/**
*
* @param prefix -
*/
setCachePrefix(prefix: string) {
this.cachePrefix = prefix;
}
}
export type PreferenceCacheType = PreferenceCache;
export { PreferenceCache };