-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-db.js
83 lines (74 loc) · 2.51 KB
/
index-db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class IndexedDB {
constructor(dbName, objectStore, version) {
this.dbName = dbName;
this.version = version;
this.objectStore = objectStore;
this.db = null;
}
async openDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, this.version);
request.onerror = event => {
reject(event.target.error);
};
request.onsuccess = event => {
this.db = event.target.result;
resolve(this.db);
};
request.onupgradeneeded = event => {
const db = event.target.result;
db.createObjectStore(this.objectStore, {
keyPath: "title",
autoIncrement: true
});
};
});
}
async getAll() {
return new Promise((resolve, reject) => {
this.executeTransaction('readonly', objectStore => {
const request = objectStore.getAll();
request.onsuccess = event => {
resolve(event.target.result);
}
})
})
}
async get(key) {
return new Promise((resolve, reject) => {
this.executeTransaction('readonly', objectStore => {
const request = objectStore.get(key);
request.onsuccess = event => {
resolve(event.target.result);
}
})
})
}
async add(value) {
return this.executeTransaction('readwrite', objectStore => objectStore.add(value));
}
async put(value) {
return this.executeTransaction('readwrite', objectStore => objectStore.put(value));
}
async delete(key) {
return this.executeTransaction('readwrite', objectStore => objectStore.delete(key));
}
async closeDB() {
this.db.close();
}
async executeTransaction(mode, transactionFn) {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(this.objectStore, mode);
transaction.onerror = event => {
reject(event.target.error);
};
transaction.oncomplete = event => {
event.target.oncomplete = async (event) => {
resolve(event.target.result);
}
};
const objectStore = transaction.objectStore(this.objectStore);
transactionFn(objectStore);
});
}
}