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

61 lines
1.6 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;
constructor(cachePrefix: string = 'vben-admin') {
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') {
const env = import.meta.env.DEV ? 'dev' : 'prod';
return `__${this.cachePrefix}-${name}-${env}__`;
}
/**
* 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 };