-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (50 loc) · 1.42 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
const Model = require('scuttlebutt/model')
const Module = require('@microverse-network/core/module')
const Collection = require('./collection')
module.exports = class Database extends Module {
constructor(options = {}) {
super(options)
this.collections = {}
this.map = new Model().on('update', (...args) => {
this.handleMapUpdate(...args)
})
}
createStreams(mux) {
super.createStreams()
this.bindMapStream(mux.createStream('map'))
}
bindStreamHandlers() {
super.bindStreamHandlers()
this.on('stream.map', stream => this.bindMapStream(stream))
}
bindMapStream(stream) {
this.debug('binding stream %s %s', stream.meta, stream.id)
stream.pipe(this.map.createStream()).pipe(stream)
}
get(name, options = {}) {
if (this.collections[name]) {
return this.collections[name]
}
options.id = name
options.db = this
const collection = new Collection(options)
this.collections[name] = collection
this.map.set(name, true)
return collection
}
list() {
const list = []
Object.keys(this.collections).forEach(name => {
return list.push(this.collections[name])
})
return list
}
handleMapUpdate([name, exists], update, source) {
if (source === this.map.id) return
if (exists && this.collections[name]) return
this.debug('database map update %s %o', name, exists)
if (exists) {
this.get(name)
}
}
}