feat: state events and query changes (#100)

This commit is contained in:
Pedro Teixeira 2017-07-07 12:56:46 +01:00 committed by David Dias
parent 2d40f3ad6a
commit 73f2f6d050

View File

@ -17,7 +17,7 @@ const multiaddr = require('multiaddr')
exports = module.exports
const OFFLINE_ERROR_MESSAGE = 'The libp2p node is not started yet'
const NOT_STARTED_ERROR_MESSAGE = 'The libp2p node is not started yet'
class Node extends EventEmitter {
constructor (_modules, _peerInfo, _peerBook, _options) {
@ -28,7 +28,7 @@ class Node extends EventEmitter {
this.modules = _modules
this.peerInfo = _peerInfo
this.peerBook = _peerBook || new PeerBook()
this.isOnline = false
this._isStarted = false
this.swarm = new Swarm(this.peerInfo, this.peerBook)
@ -156,7 +156,6 @@ class Node extends EventEmitter {
}
})
this.peerInfo.multiaddrs.replace(maOld, maNew)
const multiaddrs = this.peerInfo.multiaddrs.toArray()
transports.forEach((transport) => {
@ -174,9 +173,6 @@ class Node extends EventEmitter {
series([
(cb) => this.swarm.listen(cb),
(cb) => {
// listeners on, libp2p is on
this.isOnline = true
if (ws) {
// always add dialing on websockets
this.swarm.transport.add(ws.tag || ws.constructor.name, ws)
@ -189,10 +185,17 @@ class Node extends EventEmitter {
cb()
},
(cb) => {
// TODO: chicken-and-egg problem:
// have to set started here because DHT requires libp2p is already started
this._isStarted = true
if (this._dht) {
return this._dht.start(cb)
}
cb()
},
(cb) => {
this.emit('start')
cb()
}
], callback)
}
@ -201,7 +204,7 @@ class Node extends EventEmitter {
* Stop the libp2p node by closing its listeners and open connections
*/
stop (callback) {
this.isOnline = false
this._isStarted = false
if (this.modules.discovery) {
this.modules.discovery.forEach((discovery) => {
@ -216,16 +219,20 @@ class Node extends EventEmitter {
}
cb()
},
(cb) => this.swarm.close(cb)
(cb) => this.swarm.close(cb),
(cb) => {
this.emit('stop')
cb()
}
], callback)
}
isOn () {
return this.isOnline
isStarted () {
return this._isStarted
}
ping (peer, callback) {
assert(this.isOn(), OFFLINE_ERROR_MESSAGE)
assert(this.isStarted(), NOT_STARTED_ERROR_MESSAGE)
this._getPeerInfo(peer, (err, peerInfo) => {
if (err) {
return callback(err)
@ -236,7 +243,7 @@ class Node extends EventEmitter {
}
dial (peer, protocol, callback) {
assert(this.isOn(), OFFLINE_ERROR_MESSAGE)
assert(this.isStarted(), NOT_STARTED_ERROR_MESSAGE)
if (typeof protocol === 'function') {
callback = protocol
@ -259,7 +266,7 @@ class Node extends EventEmitter {
}
hangUp (peer, callback) {
assert(this.isOn(), OFFLINE_ERROR_MESSAGE)
assert(this.isStarted(), NOT_STARTED_ERROR_MESSAGE)
this._getPeerInfo(peer, (err, peerInfo) => {
if (err) {