-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
55 lines (48 loc) · 1.34 KB
/
index.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
var Writable = require('readable-stream').Writable
var pump = require('pump')
var sub = require('subleveldown')
module.exports = createIndex
function createIndex (ldb, opts, makeFn) {
if (typeof opts === 'function' && !makeFn) {
makeFn = opts
opts = {}
}
var stateDb = sub(ldb, 's')
var dataDb = sub(ldb, 'd', opts)
var basic = {
maxBatch: 100 || opts.maxBatch,
storeState: function (state, cb) {
state = state.toString('base64')
stateDb.put('state', state, cb)
},
fetchState: function (cb) {
stateDb.get('state', function (err, state) {
if (err && err.notFound) cb()
else if (err) cb(err)
else cb(null, Buffer.from(state, 'base64'))
})
},
clearIndex: function (cb) {
var batch = []
var maxSize = 5000
pump(dataDb.createKeyStream(), new Writable({
objectMode: true,
write: function (key, enc, next) {
batch.push({ type: 'del', key })
if (batch.length >= maxSize) {
dataDb.batch(batch, next)
} else next()
},
final: function (next) {
if (batch.length > 0) dataDb.batch(batch, next)
else next()
}
}), ondone)
function ondone (err) {
if (err) cb(err)
else cb()
}
}
}
return Object.assign({}, basic, makeFn(dataDb))
}