-
Notifications
You must be signed in to change notification settings - Fork 8
/
partial.js
78 lines (65 loc) · 1.5 KB
/
partial.js
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
// this is not super safe, only for testing
/*
format:
id => {
full,
syncedProfile,
syncedContacts,
syncedMessages,
}
*/
module.exports = function (dir) {
const { readFile, writeFile } = require('atomic-file-rw')
const debounce = require('lodash.debounce')
const path = require('path')
const DeferredPromise = require('p-defer')
const stateLoaded = DeferredPromise()
var state = {}
const filename = path.join(dir, "indexes/partial.json")
function get(cb) {
readFile(filename, (err, data) => {
if (err) {
stateLoaded.resolve()
return cb(err, {})
}
if (data)
state = JSON.parse(data).state
stateLoaded.resolve()
cb(null, state)
})
}
function atomicSave()
{
writeFile(filename, JSON.stringify({ state }), (err) => {
if (err) console.error("error saving partial", err)
})
}
var saveState = debounce(atomicSave, 1000, { leading: true })
function save(cb) {
saveState()
cb()
}
return {
updateState: function(feedId, updateFeedState, cb) {
stateLoaded.promise.then(() => {
let feedState = state[feedId] || {}
state[feedId] = Object.assign(feedState, updateFeedState)
save(cb)
})
},
removeFeed: function(feedId, cb) {
stateLoaded.promise.then(() => {
delete state[feedId]
save(cb)
})
},
get,
getSync: function() {
return state
},
remove: function(cb) {
// FIXME
//f.destroy(cb)
}
}
}