# 封装常用持久存储
# sessionStorage and localStorage
class WebStorage {
private debug: boolean;
private storage: Storage;
private prefix: string;
constructor(storageType: 'session' | 'local', prefix: string = '') {
this.storage = storageType === 'session' ? sessionStorage : localStorage;
this.prefix = prefix;
this.debug = process.env.NODE_ENV !== "production";
}
private getKey(key: string): string {
return this.prefix ? `${this.prefix}_${key}` : key;
}
public get<T>(key: string): T | null {
const fullKey = this.getKey(key);
const json = this.storage.getItem(fullKey);
try {
return json ? JSON.parse(json) as T : null;
} catch (error) {
if (this.debug) console.error(`Failed to parse storage item for key: ${fullKey}`, error);
return null;
}
}
public set<T>(key: string, data: T): void {
try {
const fullKey = this.getKey(key);
const json = JSON.stringify(data);
if (this.debug) console.log("storage.set", fullKey, data);
this.storage.setItem(fullKey, json);
} catch (error) {
if (this.debug) console.error(`Failed to set storage item for key: ${key}`, error);
}
}
public remove(key: string): void {
const fullKey = this.getKey(key);
if (this.debug) console.log("storage.remove", fullKey);
this.storage.removeItem(fullKey);
}
public clear(): void {
if (this.debug) console.log("storage.clear");
if (this.prefix) {
// 只清除带前缀的项
Object.keys(this.storage)
.filter(key => key.startsWith(`${this.prefix}_`))
.forEach(key => this.storage.removeItem(key));
} else {
this.storage.clear();
}
}
}
// 使用示例
export const sessionStorageService = new WebStorage('session', 'myApp');
export const localStorageService = new WebStorage('local', 'myApp');
# cookie
class CookieStorage {
private debug: boolean;
private prefix: string;
constructor(prefix: string = '') {
this.prefix = prefix;
this.debug = process.env.NODE_ENV !== "production";
}
private getKey(key: string): string {
return this.prefix ? `${this.prefix}_${key}` : key;
}
public get(key: string): string | undefined {
const fullKey = this.getKey(key);
const value = Cookies.get(fullKey);
if (this.debug) console.log("cookie.get", fullKey, value);
return value;
}
public set(key: string, data: string, options?: Cookies.CookieAttributes): void {
const fullKey = this.getKey(key);
if (this.debug) console.log("cookie.set", fullKey, data, options);
Cookies.set(fullKey, data, options);
}
public remove(key: string, options?: Cookies.CookieAttributes): void {
const fullKey = this.getKey(key);
if (this.debug) console.log("cookie.remove", fullKey);
Cookies.remove(fullKey, options);
}
}