export class OfflineDataHelper {
private static _instance: OfflineDataHelper;
public static get instance(): OfflineDataHelper {
if (!this._instance) {
this._instance = new OfflineDataHelper();
}
return this._instance;
}
/**
* 获取玩家数据
* @param userId
* @param dataName
* @returns
*/
public async getPlayerData(userId: string, cls: mw.TypeName<Subdata>) {
let name = cls.name || cls.constructor.name;
let subdata = new cls();
for (let i = 0; i < 3; i++) {
let result = await DataStorage.asyncGetData(userId + "_SubData_" + name);
if (result.code == DataStorageResultCode.Success) {
if (result.data) {
this.deserialize(subdata, result.data);
return subdata;
} else {
return null;
}
}
}
return null;
}
/**
* 保存玩家数据,确保Subdata是已经初始化好的
* @param userId
* @param dataName
* @param data
*/
public async setPlayerData(userId: string, subdata: Subdata) {
this.serialize(subdata);
let name = subdata.constructor.name;
for (let i = 0; i < 3; i++) {
let result = await DataStorage.asyncSetData(userId + "_SubData_" + name, subdata["dataInfo"]);
if (result == DataStorageResultCode.Success) {
break;
} else {
await TimeUtil.delaySecond(1);
}
}
}
/**
* 反序列化
* @param subdata
* @param data
*/
public deserialize(subdata: Subdata, data: any) {
subdata["deserialize"](data);
}
/**
* 序列化
* @param subdata
* @param data
* @returns
*/
public serialize(subdata: Subdata) {
return subdata["serialize"]();
}
}
|