-
Notifications
You must be signed in to change notification settings - Fork 10
/
getitems-indexeddb.js
69 lines (56 loc) · 2.38 KB
/
getitems-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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import IDBKeyRange from './idbKeyRange';
export function getItemsIndexedDB(keys/*, callback*/) {
var localforageInstance = this;
function comparer (a,b) {
return a < b ? -1 : a > b ? 1 : 0;
}
var promise = new Promise(function(resolve, reject) {
localforageInstance.ready().then(function() {
// Thanks https://hacks.mozilla.org/2014/06/breaking-the-borders-of-indexeddb/
var dbInfo = localforageInstance._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var set = keys.sort(comparer);
var keyRangeValue = IDBKeyRange.bound(keys[0], keys[keys.length - 1], false, false);
var req = store.openCursor(keyRangeValue);
var result = {};
var i = 0;
req.onsuccess = function (/*event*/) {
var cursor = req.result; // event.target.result;
if (!cursor) {
resolve(result);
return;
}
var key = cursor.key;
while (key > set[i]) {
// The cursor has passed beyond this key. Check next.
i++;
if (i === set.length) {
// There is no next. Stop searching.
resolve(result);
return;
}
}
if (key === set[i]) {
// The current cursor value should be included and we should continue
// a single step in case next item has the same key or possibly our
// next key in set.
var value = cursor.value;
if (value === undefined) {
value = null;
}
result[key] = value;
// onfound(cursor.value);
cursor.continue();
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
cursor.continue(set[i]);
}
};
req.onerror = function(/*event*/) {
reject(req.error);
};
}).catch(reject);
});
return promise;
}