demo/assets/Script/Common/StorageUtil.ts

118 lines
2.4 KiB
TypeScript

import Configs from "./Configs";
/**
*
*
* @export
* @class StorageUtil
*/
export default class StorageUtil {
private static instance: StorageUtil;
public static getInstance(): StorageUtil {
if (this.instance == null) {
this.instance = new StorageUtil();
}
return this.instance;
}
private storageMap: Map<string, unknown> = new Map();
public async setup() {
cc.log('StorageUtil setup');
}
public static prefix:string =''
/**
*
*
* @memberof StorageUtil
*/
public dumpStorageMap() {
const data: Array<{key: string, value: unknown}> = [];
this.storageMap.forEach((v, k) => {
data.push({ key: k, value: v });
});
console.table(data);
}
/**
*
*
* @memberof StorageUtil
*/
public clearCache() {
this.storageMap.clear();
}
/**
*
*
* @param key
* @param [value]
* @returns {*}
* @memberof StorageUtil
*/
public read<T>(key: Configs.BStorageKey, value?: T): T {
let result = value;
let realKey = this.getKey(key);
if (this.storageMap.has(realKey)) {
return this.storageMap.get(realKey) as T;
}
const userData = JSON.parse(cc.sys.localStorage.getItem(realKey));
if (userData !== null) {
result = userData;
}
this.storageMap.set(realKey, result);
return result;
}
/**
*
*
* @param key
* @param value
* @memberof StorageUtil
*/
public write<T>(key: Configs.BStorageKey, value: T) {
let realKey = this.getKey(key);
this.storageMap.set(realKey, value);
cc.sys.localStorage.setItem(realKey, JSON.stringify(value || null));
}
/**
*
*
* @param key
* @memberof StorageUtil
*/
public remove(key: Configs.BStorageKey) {
let realKey = this.getKey(key);
this.storageMap.delete(realKey);
cc.sys.localStorage.removeItem(realKey);
}
/**
*
*
* @memberof StorageUtil
*/
public clear() {
this.storageMap.clear();
cc.sys.localStorage.clear();
}
/**
* key
*
* @private
* @param key
* @returns {*}
* @memberof StorageUtil
*/
private getKey(key: Configs.BStorageKey): string {
return `${StorageUtil.prefix}_${key}`;
}
}