-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
67 lines (53 loc) · 1.22 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
56
57
58
59
60
61
62
63
64
65
66
67
'use strict'
const { Readable } = require('stream')
const ltgt = require('ltgt')
class Live extends Readable {
constructor (db, opts = {}) {
super({ objectMode: true })
this.db = db
this.buf = []
this.opts = opts
this.onput = this.onput.bind(this)
this.ondel = this.ondel.bind(this)
this.onbatch = this.onbatch.bind(this)
db.on('put', this.onput)
db.on('del', this.ondel)
db.on('batch', this.onbatch)
db
.createReadStream(opts)
.on('data', ({ key, value }) => this.onput(key, value))
}
start () {
while (this.buf.length) {
if (!this.push(this.buf.shift())) {
break
}
}
}
_read () {
this.start()
}
op (op) {
if (ltgt.contains(this.opts, op.key)) {
this.buf.push(op)
if (this.buf.length === 1) this.start()
}
}
onput (key, value) {
this.op({ type: 'put', key, value })
}
ondel (key) {
this.op({ type: 'del', key })
}
onbatch (ops) {
for (const op of ops) this.op(op)
}
_destroy (_, cb) {
this.db.removeListener('put', this.onput)
this.db.removeListener('del', this.ondel)
this.db.removeListener('batch', this.onbatch)
this.buf = []
cb()
}
}
module.exports = Live