Handle indexeddb termination

Also reset and reopen mldata db after clearing
This commit is contained in:
Shailesh Pandit 2022-01-31 12:53:37 +05:30
parent 0fe22bd591
commit 5b7c8a2cf7

View file

@ -47,15 +47,25 @@ interface MLDb extends DBSchema {
} }
class MLIDbStorage { class MLIDbStorage {
public db: Promise<IDBPDatabase<MLDb>>; public _db: Promise<IDBPDatabase<MLDb>>;
constructor() { constructor() {
if (!runningInBrowser()) { if (!runningInBrowser()) {
return; return;
} }
this.db = openDB<MLDb>(MLDATA_DB_NAME, 3, { this.db;
upgrade(db, oldVersion, newVersion, tx) { }
private openDB(): Promise<IDBPDatabase<MLDb>> {
const mlIDbStorage = this;
return openDB<MLDb>(MLDATA_DB_NAME, 3, {
async terminated() {
console.log('Indexed DB terminated');
mlIDbStorage._db = undefined;
await mlIDbStorage.db;
},
async upgrade(db, oldVersion, newVersion, tx) {
if (oldVersion < 1) { if (oldVersion < 1) {
const filesStore = db.createObjectStore('files', { const filesStore = db.createObjectStore('files', {
keyPath: 'fileId', keyPath: 'fileId',
@ -77,29 +87,39 @@ class MLIDbStorage {
// TODO: update configs if version is updated in defaults // TODO: update configs if version is updated in defaults
db.createObjectStore('configs'); db.createObjectStore('configs');
tx.objectStore('configs').add( await tx
DEFAULT_ML_SYNC_JOB_CONFIG, .objectStore('configs')
ML_SYNC_JOB_CONFIG_NAME .add(
); DEFAULT_ML_SYNC_JOB_CONFIG,
tx.objectStore('configs').add( ML_SYNC_JOB_CONFIG_NAME
DEFAULT_ML_SYNC_CONFIG, );
ML_SYNC_CONFIG_NAME await tx
); .objectStore('configs')
.add(DEFAULT_ML_SYNC_CONFIG, ML_SYNC_CONFIG_NAME);
} }
if (oldVersion < 3) { if (oldVersion < 3) {
tx.objectStore('configs').add( await tx
DEFAULT_ML_SEARCH_CONFIG, .objectStore('configs')
ML_SEARCH_CONFIG_NAME .add(DEFAULT_ML_SEARCH_CONFIG, ML_SEARCH_CONFIG_NAME);
);
} }
}, },
}); });
} }
public get db(): Promise<IDBPDatabase<MLDb>> {
if (!this._db) {
this._db = this.openDB();
}
return this._db;
}
public async clearMLDB() { public async clearMLDB() {
const db = await this.db; const db = await this.db;
db.close(); db.close();
return deleteDB(MLDATA_DB_NAME); await deleteDB(MLDATA_DB_NAME);
this._db = undefined;
await this.db;
} }
public async getAllFileIds() { public async getAllFileIds() {