aether-shards/src/core/Persistence.js

72 lines
1.9 KiB
JavaScript
Raw Normal View History

/**
* Persistence.js
* Handles asynchronous saving and loading using IndexedDB.
*/
const DB_NAME = "AetherShardsDB";
const STORE_NAME = "Runs";
const VERSION = 1;
export class Persistence {
constructor() {
this.db = null;
}
async init() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, VERSION);
request.onerror = (e) => reject("DB Error: " + e.target.error);
request.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: "id" });
}
};
request.onsuccess = (e) => {
this.db = e.target.result;
resolve();
};
});
}
async saveRun(runData) {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const tx = this.db.transaction([STORE_NAME], "readwrite");
const store = tx.objectStore(STORE_NAME);
// Always use ID 'active_run' for the single active session
runData.id = "active_run";
const req = store.put(runData);
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
async loadRun() {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const tx = this.db.transaction([STORE_NAME], "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get("active_run");
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async clearRun() {
if (!this.db) await this.init();
return new Promise((resolve, reject) => {
const tx = this.db.transaction([STORE_NAME], "readwrite");
const store = tx.objectStore(STORE_NAME);
const req = store.delete("active_run");
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
}