38 lines
1.9 KiB
TypeScript
38 lines
1.9 KiB
TypeScript
/** Resident cache bridge: progress saves never import the lazy UI bundle. */
|
|
export default class WeeklyCache {
|
|
static scope(server: string, uid: string): string { return server.replace(/\/+$/, '') + ':' + uid; }
|
|
static key(scope: string): string { return 'weeklyCompetition:cache:v1:' + scope; }
|
|
static revision(scope: string): string {
|
|
return cc.sys.localStorage.getItem(this.key(scope) + ':revision') || '';
|
|
}
|
|
static invalidate(scope: string): void {
|
|
cc.sys.localStorage.setItem(this.key(scope) + ':revision', Date.now() + ':' + Math.random());
|
|
cc.sys.localStorage.removeItem(this.key(scope));
|
|
}
|
|
static read(scope: string): any {
|
|
try {
|
|
const raw = cc.sys.localStorage.getItem(this.key(scope));
|
|
if (!raw) return null;
|
|
const cache = JSON.parse(raw), now = Date.now();
|
|
if (cache.revision !== this.revision(scope) || !Number.isFinite(cache.expiresAt)
|
|
|| !Number.isFinite(cache.lastSeen) || !Number.isFinite(cache.startedAt)
|
|
|| now < cache.lastSeen || now >= cache.expiresAt) {
|
|
cc.sys.localStorage.removeItem(this.key(scope));
|
|
return null;
|
|
}
|
|
cache.lastSeen = now;
|
|
cc.sys.localStorage.setItem(this.key(scope), JSON.stringify(cache));
|
|
return cache;
|
|
} catch (_) { return null; }
|
|
}
|
|
static write(scope: string, data: any, startedAt: number, revision: string): any {
|
|
const now = Date.now();
|
|
const ttl = Math.max(0, Math.min(data.cacheTtlSeconds * 1000, data.currentWeek.endAt - data.serverTime));
|
|
const cache = { data, startedAt, lastSeen: now, expiresAt: startedAt + ttl, revision };
|
|
if (now >= startedAt && revision === this.revision(scope)) {
|
|
cc.sys.localStorage.setItem(this.key(scope), JSON.stringify(cache));
|
|
}
|
|
return cache;
|
|
}
|
|
}
|