hydrogen-web/prototypes/chrome-keys.html

74 lines
2.2 KiB
HTML
Raw Permalink Normal View History

2019-02-18 04:28:01 +05:30
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="module">
function reqAsPromise(req) {
return new Promise((resolve, reject) => {
req.addEventListener("success", event => resolve(event.target.result));
req.addEventListener("error", event => reject(event.target.error));
});
}
function txnAsPromise(txn) {
return new Promise((resolve, reject) => {
txn.addEventListener("complete", resolve);
txn.addEventListener("abort", reject);
});
}
export function readAll(cursor) {
return new Promise((resolve, reject) => {
const results = [];
cursor.onerror = (event) => {
reject(new Error("Query failed: " + event.target.errorCode));
};
cursor.onsuccess = (event) => {
const cursor = event.target.result;
if (!cursor) {
resolve(results);
} else {
results.push(cursor.value);
cursor.continue();
}
};
});
}
async function main() {
let isNew = false;
const openReq = window.indexedDB.open("composed_binary_keys_test", 1);
openReq.onupgradeneeded = (ev) => {
const db = ev.target.result;
db.createObjectStore("test", {keyPath: ["strKey", "binKey"]});
isNew = true;
};
const db = await reqAsPromise(openReq);
// fill test store with some initial data
if (isNew) {
const txn = db.transaction("test", "readwrite");
const store = txn.objectStore("test");
store.add({strKey: "abc", binKey: new Uint8Array([0x0F, 0x00, 0x10, 0x00]).buffer});
store.add({strKey: "def", binKey: new Uint8Array([0x00, 0x10, 0x00, 0x00]).buffer});
store.add({strKey: "def", binKey: new Uint8Array([0xFF, 0x10, 0x00, 0x00]).buffer});
store.add({strKey: "ghi", binKey: new Uint8Array([0x00, 0x00, 0x40, 0x00]).buffer});
await txnAsPromise(txn);
}
const txn = db.transaction("test", "readonly");
const store = txn.objectStore("test");
const defRange = IDBKeyRange.bound(
["def", new Uint8Array([0x00, 0x00, 0x00, 0x00]).buffer],
["def", new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]).buffer],
true, true,
);
const defValues = await readAll(store.openCursor(defRange, "prev"));
console.log(defValues);
}
main();
</script>
</body>
</html>