-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathepvStorePersistentIdb.js
More file actions
74 lines (72 loc) · 2.2 KB
/
Copy pathepvStorePersistentIdb.js
File metadata and controls
74 lines (72 loc) · 2.2 KB
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
const idb = require("idb")
const { set, unset } = require("./kkvHelpers")
const epvStore = require("./epvStore")
const create = require("lodash/create")
const delay = (i, fn) =>
new Promise((resolve, reject) =>
setTimeout(() => fn().then(resolve, reject), i)
)
module.exports = storeName => {
const data = new Map()
let loadCount = 0
let db
return idb
.open("data", 1, upgradeDB => {
upgradeDB.createObjectStore("data")
})
.then(res => {
db = res
const tx = db.transaction("data", "readonly")
tx.objectStore("data").iterateCursor(cursor => {
if (!cursor) return
const [k1, k2] = JSON.parse(cursor.key)
set(data, k1, k2, cursor.value)
loadCount++
return cursor.continue()
})
return tx.complete.catch(err =>
console.error("error persisting patch", err)
)
})
.then(() => {
console.log(`${loadCount} entries from ${storeName} store loaded`)
const store = epvStore(data)
const patchAndSave = patch => {
// call memory store patch
store.patch(patch)
// and then persist it
const keys = Object.keys(patch)
console.log(`patch with ${keys.length} keys`)
return Promise.all(
keys.map((k1, i) =>
delay(i, () => {
console.log("writing patch key in idb", i)
const tx = db.transaction("data", "readwrite")
const idbStore = tx.objectStore("data")
const subPatch = patch[k1]
const subKeys = Object.keys(subPatch)
subKeys.forEach(k2 => {
const key = JSON.stringify([k1, k2])
const value = subPatch[k2]
if (value == null) {
idbStore.delete(key)
} else {
idbStore.put(value, key)
}
})
return tx.complete
})
)
)
}
return create(store, {
patch: patchAndSave,
clearAllData: () => {
const tx = db.transaction("data", "readwrite")
const idbStore = tx.objectStore("data")
idbStore.clear()
return tx.complete
},
})
})
}