Skip to content

Commit cc2bea8

Browse files
authored
[feat] Improves IndexedDB initialization and recovery (#278)
1 parent ae24b16 commit cc2bea8

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

src/Services/DB.ts

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,55 @@
1-
import { openDB } from "idb";
1+
import { deleteDB, openDB } from "idb";
22
import { Dic } from "~/Helpers/Entities";
33

4+
const DB_VERSION = 2;
5+
46
/**
57
* @author Aloento
68
* @since 1.0.0
7-
* @version 0.1.0
9+
* @version 0.2.0
810
*/
911
export class DB<T> {
1012
public Ins: T;
13+
private dbName: string;
14+
private storeName: string;
1115

1216
constructor(factory: () => T) {
1317
this.Ins = factory();
18+
this.dbName = Dic.Name;
19+
this.storeName = Dic.Name;
1420
}
1521

1622
public async init() {
17-
return openDB(Dic.Name, 1, {
18-
upgrade(db) {
19-
db.createObjectStore(Dic.Name);
20-
},
21-
});
23+
try {
24+
return openDB(this.dbName, DB_VERSION, {
25+
upgrade(db) {
26+
if (db.objectStoreNames.contains(Dic.Name)) {
27+
db.deleteObjectStore(Dic.Name);
28+
}
29+
db.createObjectStore(Dic.Name);
30+
},
31+
});
32+
} catch (error) {
33+
await deleteDB(this.dbName);
34+
35+
return openDB(this.dbName, DB_VERSION, {
36+
upgrade(db) {
37+
db.createObjectStore(Dic.Name);
38+
},
39+
});
40+
}
2241
}
2342

2443
public async save(key: string, data = this.Ins) {
2544
this.Ins = data;
2645
const db = await this.init();
27-
await db.put(Dic.Name, data, key);
46+
await db.put(this.storeName, data, key);
2847
db.close();
2948
}
3049

3150
public async load(key: string) {
3251
const db = await this.init();
33-
const res = await db.get(Dic.Name, key) as T;
52+
const res = await db.get(this.storeName, key) as T;
3453
if (res) {
3554
this.Ins = res;
3655
}

0 commit comments

Comments
 (0)