class Database { constructor(name, version) { this.isInit = false; this.name = name; this.version = version; this.errored = false; this.db; this.prepareDB(); } async prepareDB() { if (this.isInit || this.errored) { return; } let req = this.db = indexedDB.open(this.name, this.version); req.onerror = DatabaseHandler.onError.bind(this); req.onsuccess = DatabaseHandler.onSuccess.bind(this); req.onupgradeneeded = DatabaseHandler.onUpgrade.bind(this); req.onblocked = DatabaseHandler.onBlocked.bind(this); } async set(key, data, store) { data['key'] = key; return await this.run('put', data, store); } async get(key, store) { return await this.run('get', key, store); } async remove(key, store) { return await this.run('delete', key, store); } check() { return !(!this.isInit || this.errored); } async getTX(store) { return await this.db.transaction([store], "readwrite") } async getObjectStore(tx, store) { return await tx.objectStore(store) } async run(action, key, store) { if (this.check()) { let tx = await this.getTX(store); let obj = await this.getObjectStore(tx, store); let data = await this.request(obj[action](key)); await tx.complete return await data; } return null; } request(req) { return new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } } class DatabaseHandler { static onError(e) { this.errored = true; eventHandler.sendData("databaseError", "error", e.message); } static onSuccess(e) { this.db = this.db.result; this.isInit = true; eventHandler.sendData("databaseCreated", "success", ""); eventHandler.handleEvent({ data: { cmd: 'dbReady-' + this.name, data: this.db } }); } static onUpgrade(e) { eventHandler.sendData("databaseUpgradeNeeded", "info", e.message); eventHandler.handleEvent({ data: { cmd: 'dbUpgrade-' + this.name, data: this.db } }); } static onBlocked(e) { eventHandler.sendData("databaseBlocked", "error", e.message); } }