blob: 603f6f0b8e0667ad7d93daca16e274b1048e5668 (
plain) (
blame)
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
|
const Dnode = require('dnode')
const ObservableStore = require('./index')
const endOfStream = require('end-of-stream')
//
// RemoteStore
//
// connects to a HostStore and receives its latest state
//
class RemoteStore extends ObservableStore {
constructor (initState, opts) {
super(initState)
this._opts = opts || {}
this._remote = null
}
put (newState) {
if (!this._remote) throw new Error('RemoteStore - "put" called before connection to HostStore')
this._put(newState)
this._remote.put(newState)
}
createStream () {
const self = this
const dnode = Dnode({
put: (newState) => self._put(newState),
})
// listen for connection to remote
dnode.once('remote', (remote) => {
// setup connection lifecycle
self._onConnect(remote)
endOfStream(dnode, () => self._onDisconnect())
})
return dnode
}
_onConnect (remote) {
this._remote = remote
this.emit('connected')
}
_onDisconnect () {
this._remote = null
this.emit('disconnected')
}
}
module.exports = RemoteStore
|