130 lines
2.4 KiB
TypeScript
130 lines
2.4 KiB
TypeScript
export default class Storage {
|
|
|
|
/**
|
|
* 获取为布尔值
|
|
*
|
|
* @param key 键
|
|
* @returns 布尔值
|
|
*/
|
|
public static is(key: string): boolean {
|
|
return this.getString(key) === "true";
|
|
}
|
|
|
|
/**
|
|
* 获取为布尔值并取反
|
|
*
|
|
* @param key 键
|
|
* @returns 布尔值
|
|
*/
|
|
public static not(key: string): boolean {
|
|
return !this.is(key);
|
|
}
|
|
|
|
/**
|
|
* 读取为指定对象
|
|
*
|
|
* @template T 对象类型
|
|
* @param key 键
|
|
* @returns {T | undefined} 返回对象
|
|
*/
|
|
public static getObject<T>(key: string): T {
|
|
if (this.has(key)) {
|
|
return this.getJSON(key) as T;
|
|
}
|
|
throw Error(`not found ${key}`);
|
|
}
|
|
|
|
/**
|
|
* 获取值,如果没有则储存并使用默认值
|
|
*
|
|
* @template T 默认值类型
|
|
* @param key 键
|
|
* @param def 默认值
|
|
* @return {T} 对象
|
|
*/
|
|
public static getDefault<T>(key: string, def: T): T {
|
|
if (this.has(key)) {
|
|
return this.getJSON(key) as T;
|
|
}
|
|
this.setObject(key, def);
|
|
return def;
|
|
}
|
|
|
|
/**
|
|
* 获取为 JSON
|
|
*
|
|
* @param key 键
|
|
* @returns JSON 对象
|
|
*/
|
|
public static getJSON(key: string) {
|
|
return JSON.parse(this.getString(key));
|
|
}
|
|
|
|
/**
|
|
* 获取为字符串(其他获取方式一般经过这个方法,找不到配置或配置值无效时会抛错)
|
|
*
|
|
* @param key 键
|
|
* @returns 字符串
|
|
*/
|
|
public static getString(key: string): string {
|
|
const value = localStorage.getItem(key);
|
|
if (value) {
|
|
return value;
|
|
}
|
|
throw new Error(`not found: ${key}, ${value}`);
|
|
}
|
|
|
|
/**
|
|
* 是否存在某配置
|
|
*
|
|
* @param key 键
|
|
* @returns true 为存在
|
|
*/
|
|
public static has(key: string): boolean {
|
|
return localStorage.getItem(key) !== undefined && localStorage.getItem(key) !== null;
|
|
}
|
|
|
|
/**
|
|
* 设置值
|
|
*
|
|
* @param key 键
|
|
* @param value 值
|
|
*/
|
|
public static setObject(key: string, value: any) {
|
|
if (value instanceof Object || value instanceof Array) {
|
|
this.setJSON(key, value);
|
|
} else {
|
|
this.setString(key, value);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 设置 JSON 值
|
|
*
|
|
* @param key 键
|
|
* @param json JSON 字符串
|
|
*/
|
|
public static setJSON(key: string, json: any) {
|
|
localStorage.setItem(key, JSON.stringify(json));
|
|
}
|
|
|
|
/**
|
|
* 设置值
|
|
*
|
|
* @param key 键
|
|
* @param value 值
|
|
*/
|
|
public static setString(key: string, value: any) {
|
|
localStorage.setItem(key, value);
|
|
}
|
|
|
|
/**
|
|
* 移除属性
|
|
*
|
|
* @param key 键
|
|
*/
|
|
public static remove(key: string) {
|
|
localStorage.removeItem(key);
|
|
}
|
|
}
|