forked from mafintosh/hypercore-multi-key
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
48 lines (37 loc) · 1.17 KB
/
index.js
File metadata and controls
48 lines (37 loc) · 1.17 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
const crypto = require('@ddatabase/crypto')
const ddatabase = require('ddatabase')
const storage = require('./storage')
module.exports = multiKey
function multiKey (feed, keyPair, opts) {
if (!keyPair) keyPair = crypto.keyPair()
const key = keyPair.key || keyPair.publicKey
const other = ddatabase(storage(feed, keyPair), key, opts)
feed.ready(function () {
other.ready(function () {
other.bitfield = feed.bitfield
other.tree = feed.tree
})
})
feed.on('download', ondownload)
feed.on('append', onappend)
other.on('close', function () {
feed.removeListener('download', ondownload)
feed.removeListener('append', onappend)
})
return other
function ondownload (index, data) {
other._announce({ start: index }, null)
other.emit('download', index, data, null)
}
function onappend () {
const offset = other.length
other.length = feed.length
other.byteLength = feed.byteLength
if (!feed.writable) return other.emit('append')
const message = other.length - offset > 1
? { start: offset, length: other.length - offset }
: { start: offset }
other._announce(message)
other.emit('append')
}
}