diff options
Diffstat (limited to 'storage.html')
-rw-r--r-- | storage.html | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/storage.html b/storage.html new file mode 100644 index 0000000..f9e9bee --- /dev/null +++ b/storage.html @@ -0,0 +1,60 @@ +<script> +// const ṡ = { +// get: x => JSON.parse(localStorage.getItem("~simon/onpoint/"+x)), +// set: (x, y) => localStorage.setItem("~simon/onpoint/"+x, JSON.stringify(y)), +// } + +const ṡ = { + db: "~simon/onpoint", + store: "data", // keep in sync with schema + schema: 1, + + open() { + return new Promise((res, rej) => { + let req = indexedDB.open(this.db, this.schema) + req.onerror = e => rej(req.error) + req.onupgradeneeded = + e => e.target.result + .createObjectStore(this.store, {keyPath: "id"}) + req.onsuccess = e => res(e.target.result) + }) + }, + + call_store(store, meth, ...args) { + return new Promise((res, rej) => { + let req = store[meth](...args) + req.onerror = e => rej(req.error) + req.onsuccess = e => res(req.result) + }) + }, + + async get_store(type) { + return (await this.open()) + .transaction([this.store], type) + .objectStore(this.store) + }, + + async set(x, y) { + return this.call_store( + await this.get_store("readwrite"), "put", {id: x, data: y}) + }, + + async get(x) { + return ( + await this.call_store( + await this.get_store(), "get", x))?.data + }, + + async get_all(keys) { + let entries = + await Promise.all(keys.map(async k => [k, await this.get(k)])) + return Object.fromEntries(entries) + }, + + set_all(obj) { + return Object.entries(obj) + .map(([k, v]) => this.set(k, v)) + .ǀ(Promise.all) + }, +} +</script> |