-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathepvStorePersistentIdbWrapper.js
More file actions
110 lines (106 loc) · 2.79 KB
/
Copy pathepvStorePersistentIdbWrapper.js
File metadata and controls
110 lines (106 loc) · 2.79 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const IDBStore = require("idb-wrapper")
const { set } = require("./kkvHelpers")
const epvStore = require("./epvStore")
const create = require("lodash/create")
const chunk = require("lodash/chunk")
const { observable } = require("kobs")
const tasksQueue = waitingCb => {
let waitingValue = true
const waiting = newValue => {
waitingValue = newValue
waitingCb && waitingCb(waitingValue)
}
const tasks = []
const execNext = () => {
if (tasks.length == 0) {
waiting(true)
return
}
const task = tasks.shift()
task(execNext)
}
const push = task => {
tasks.push(task)
if (waitingValue) {
waiting(false)
execNext()
}
}
return push
}
module.exports = storeName => {
const data = new Map()
let db
let loadCount = 0
let persisting = observable(false, "persisting")
return new Promise((resolve, reject) => {
db = new IDBStore({
storeName,
autoIncrement: false,
onStoreReady: resolve,
keyPath: null,
onError: reject,
})
})
.then(
() =>
new Promise((resolve, reject) => {
//auto-load
db.iterate(
(value, { primaryKey: key }) => {
const [k1, k2] = JSON.parse(key)
set(data, k1, k2, value)
loadCount++
},
{
onError: reject,
onEnd: resolve,
}
)
})
)
.then(() => {
console.log(`${loadCount} entries from ${storeName} store loaded`)
const store = epvStore(data)
const scheduleTask = tasksQueue(waiting => persisting(!waiting))
const patchAndSave = patch => {
// call memory store patch
store.patch(patch)
// and then persist it
chunk(Object.keys(patch), 100).forEach((keys, i) => {
const batch = []
keys.forEach(k1 => {
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) {
batch.push({ type: "remove", key })
} else {
batch.push({ type: "put", key, value })
}
})
})
scheduleTask(next =>
db.batch(
batch,
() => {
console.log(`patch chunck persisted`, i)
next()
},
err => console.error("error persisting patch chunk", i, err)
)
)
})
}
return create(store, {
patch: patchAndSave,
persisting,
clearAllData: () =>
new Promise((resolve, reject) => {
db.clear(resolve, reject)
}),
})
})
}