|
1 | | -import { openDB } from "idb"; |
| 1 | +import { deleteDB, openDB } from "idb"; |
2 | 2 | import { Dic } from "~/Helpers/Entities"; |
3 | 3 |
|
| 4 | +const DB_VERSION = 2; |
| 5 | + |
4 | 6 | /** |
5 | 7 | * @author Aloento |
6 | 8 | * @since 1.0.0 |
7 | | - * @version 0.1.0 |
| 9 | + * @version 0.2.0 |
8 | 10 | */ |
9 | 11 | export class DB<T> { |
10 | 12 | public Ins: T; |
| 13 | + private dbName: string; |
| 14 | + private storeName: string; |
11 | 15 |
|
12 | 16 | constructor(factory: () => T) { |
13 | 17 | this.Ins = factory(); |
| 18 | + this.dbName = Dic.Name; |
| 19 | + this.storeName = Dic.Name; |
14 | 20 | } |
15 | 21 |
|
16 | 22 | 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 | + } |
22 | 41 | } |
23 | 42 |
|
24 | 43 | public async save(key: string, data = this.Ins) { |
25 | 44 | this.Ins = data; |
26 | 45 | const db = await this.init(); |
27 | | - await db.put(Dic.Name, data, key); |
| 46 | + await db.put(this.storeName, data, key); |
28 | 47 | db.close(); |
29 | 48 | } |
30 | 49 |
|
31 | 50 | public async load(key: string) { |
32 | 51 | 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; |
34 | 53 | if (res) { |
35 | 54 | this.Ins = res; |
36 | 55 | } |
|
0 commit comments