Files
18xchat/assets/Scripts/chat18x/payment/PendingOrderRepo.ts
T

58 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-08-19 18:32:09 +08:00
/**
* 本地持久化未决订单,断线/重启后可恢复
*
*/
import { sys } from "cc";
import type { PendingOrder } from "./types";
export class PendingOrderRepo {
private static _instance: PendingOrderRepo | null = null; // 私有静态实例
private static KEY = "pay:pending_orders"; // 本地存储的 key
private cache: PendingOrder[] | null = null; // 本地缓存
// 私有构造函数,禁止外部直接实例化
private constructor() {}
// 获取唯一实例
public static get instance(): PendingOrderRepo {
if (!PendingOrderRepo._instance) {
PendingOrderRepo._instance = new PendingOrderRepo();
}
return PendingOrderRepo._instance;
}
// 加载数据
private load(): PendingOrder[] {
if (this.cache) return this.cache; // 如果有缓存,直接返回
const raw = sys.localStorage.getItem(PendingOrderRepo.KEY); // 从 localStorage 获取数据
if (!raw) return (this.cache = []); // 如果没有数据,返回空数组
try { return (this.cache = JSON.parse(raw) || []); } catch { return (this.cache = []); } // 解析失败时返回空数组
}
// 保存数据
private save(list: PendingOrder[]) {
this.cache = list; // 更新缓存
sys.localStorage.setItem(PendingOrderRepo.KEY, JSON.stringify(list)); // 存储到 localStorage
}
// 添加未决订单
add(o: PendingOrder) {
const list = this.load();
list.unshift(o); // 将新订单添加到数组前面
this.save(list.slice(0, 10)); // 保存最多 10 条订单
}
// 删除指定订单
remove(orderId: string) {
const list = this.load().filter(x => x.orderId !== orderId); // 过滤掉指定订单
this.save(list); // 更新数据
}
// 获取所有未决订单
all(): PendingOrder[] {
return this.load(); // 返回加载的数据
}
}