forked from jakearchibald/idb-keyval
-
Notifications
You must be signed in to change notification settings - Fork 0
/
idb-keyval.js
91 lines (84 loc) · 2.33 KB
/
idb-keyval.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
84
85
86
87
88
89
90
91
(function() {
'use strict';
var db;
function getDB() {
if (!db) {
db = new Promise(function(resolve, reject) {
var openreq = indexedDB.open('keyval-store', 1);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function() {
// First time setup: create an empty object store
openreq.result.createObjectStore('keyval');
};
openreq.onsuccess = function() {
resolve(openreq.result);
};
});
}
return db;
}
function withStore(type, callback) {
return getDB().then(function(db) {
return new Promise(function(resolve, reject) {
var transaction = db.transaction('keyval', type);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(transaction.error);
};
callback(transaction.objectStore('keyval'));
});
});
}
var idbKeyval = {
get: function(key) {
var req;
return withStore('readonly', function(store) {
req = store.get(key);
}).then(function() {
return req.result;
});
},
set: function(key, value) {
return withStore('readwrite', function(store) {
store.put(value, key);
});
},
delete: function(key) {
return withStore('readwrite', function(store) {
store.delete(key);
});
},
clear: function() {
return withStore('readwrite', function(store) {
store.clear();
});
},
keys: function() {
var keys = [];
return withStore('readonly', function(store) {
// This would be store.getAllKeys(), but it isn't supported by Edge or Safari.
// And openKeyCursor isn't supported by Safari.
(store.openKeyCursor || store.openCursor).call(store).onsuccess = function() {
if (!this.result) return;
keys.push(this.result.key);
this.result.continue();
};
}).then(function() {
return keys;
});
}
};
if (typeof module != 'undefined' && module.exports) {
module.exports = idbKeyval;
} else if (typeof define === 'function' && define.amd) {
define('idbKeyval', [], function() {
return idbKeyval;
});
} else {
self.idbKeyval = idbKeyval;
}
}());