Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add discover function
  • Loading branch information
mkg20001 committed May 19, 2018
commit bccd5f56610f6679296438eabf75f8c2ae57eab3
39 changes: 31 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class RendezvousDiscovery {
this.rpc.push(rpc)
this.rpcById[rpc.id] = rpc

rpc.cursors = {}
rpc.cookies = {}
rpc.registrations = {}

log('add new peer %s', rpc.id)
Expand Down Expand Up @@ -81,24 +81,47 @@ class RendezvousDiscovery {
this._getState(peer.id.toBytes()).register(ns, peer, ttl, cb)
}

discover (ns, limit, /* cookie, */ cb) {
/* if (typeof cookie === 'function') {
cb = cookie
cookie = Buffer.from('')
} */
discover (ns, limit, cb) {
if (typeof limit === 'function') {
// cookie = Buffer.from('')
cb = limit
limit = 0
}
if (typeof ns === 'function') {
// cookie = Buffer.from('')
limit = 0
cb = ns
ns = null
}

this._cleanPeers()

let peers = this.rpc.slice(0)

function getMore (cb) {
let peer = peers.shift()
if (!peer) return cb(new Error('No more peers left to query!'))
let cookie = peer.cookies[ns]
peer.discover(ns, limit, cookie, (err, res) => {
if (err) return cb(err)
peer.cookies[ns] = res.cookie
return cb(null, res.peers)
})
}

let has = []

function get () {
if ((limit && has.length < limit) || !peers.length) {
return cb(null, has)
}

getMore((err, peers) => {
if (err) log('discover:%s: %s', ns, err)
if (peers && peers.length) has = has.concat(peers)
get()
})
}

get()
}

unregister (ns, id) {
Expand Down
6 changes: 3 additions & 3 deletions test/discovery.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ describe('discovery', () => {
client.discover('hello', (err, res) => {
if (err) return done(err)
expect(err).to.not.exist()
expect(res.peers).to.have.lengthOf(1)
expect(res.peers[0].id.toB58String()).to.equal(client2.swarm.peerInfo.id.toB58String())
expect(res).to.have.lengthOf(1)
expect(res[0].id.toB58String()).to.equal(client2.swarm.peerInfo.id.toB58String())
done()
})
})
Expand All @@ -51,7 +51,7 @@ describe('discovery', () => {
client.discover('hello', (err, res) => {
if (err) return done(err)
expect(err).to.not.exist()
expect(res.peers).to.have.lengthOf(0)
expect(res).to.have.lengthOf(0)
done()
})
})
Expand Down