summaryrefslogtreecommitdiff
path: root/storage.html
blob: f9e9beebf9a176b0528e384c3e45051adc66973a (plain)
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
<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>