-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexeddb.js
47 lines (38 loc) · 1.67 KB
/
indexeddb.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
helper = {
IndexedDB: {
open: function(dbName, version, upgradeCallback) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, version);
request.onerror = event => reject('IndexedDB error: ' + event.target.error);
request.onsuccess = event => resolve(event.target.result);
if (upgradeCallback) {
request.onupgradeneeded = event => upgradeCallback(event.target.result);
}
});
},
_performTransaction: function(db, storeName, mode, operation) {
return new Promise((resolve, reject) => {
const transaction = db.transaction([storeName], mode);
const store = transaction.objectStore(storeName);
const request = operation(store);
request.onerror = event => reject(`Transaction error: ${event.target.error}`);
request.onsuccess = event => resolve(event.target.result);
});
},
add: function(db, storeName, data) {
return this._performTransaction(db, storeName, 'readwrite', store => store.add(data));
},
get: function(db, storeName, key) {
return this._performTransaction(db, storeName, 'readonly', store => store.get(key));
},
update: function(db, storeName, key, data) {
return this._performTransaction(db, storeName, 'readwrite', store => store.put(data, key));
},
delete: function(db, storeName, key) {
return this._performTransaction(db, storeName, 'readwrite', store => store.delete(key));
},
getAll: function(db, storeName) {
return this._performTransaction(db, storeName, 'readonly', store => store.getAll());
}
}
};