diff --git a/src/index.js b/src/index.js index 657cfd71..e3948392 100644 --- a/src/index.js +++ b/src/index.js @@ -192,6 +192,7 @@ class KadDHT { * @param {Buffer} key * @param {Object} options - get options * @param {number} options.maxTimeout - optional timeout (default: 60000) + * @param {boolean} options.selectFirst - select first value found (default: false) * @param {function(Error, Buffer)} callback * @returns {void} */ @@ -221,6 +222,7 @@ class KadDHT { * @param {number} nvals * @param {Object} options - get options * @param {number} options.maxTimeout - optional timeout (default: 60000) + * @param {boolean} options.selectFirst - select first value found (default: false) * @param {function(Error, Array<{from: PeerId, val: Buffer}>)} callback * @returns {void} */ diff --git a/src/private.js b/src/private.js index 39ad0bed..ec314787 100644 --- a/src/private.js +++ b/src/private.js @@ -260,6 +260,7 @@ module.exports = (dht) => ({ * @param {Buffer} key * @param {Object} options - get options * @param {number} options.maxTimeout - optional timeout (default: 60000) + * @param {boolean} options.selectFirst - select first value found (default: false) * @param {function(Error, Record)} callback * @returns {void} * @@ -271,7 +272,7 @@ module.exports = (dht) => ({ (cb) => dht.getMany(key, 16, options.maxTimeout, cb), (vals, cb) => { const recs = vals.map((v) => v.val) - const i = libp2pRecord.selection.bestRecord(dht.selectors, key, recs) + const i = options.selectFirst ? 0 : libp2pRecord.selection.bestRecord(dht.selectors, key, recs) const best = recs[i] dht._log('GetValue %b %s', key, best) diff --git a/test/kad-dht.spec.js b/test/kad-dht.spec.js index 3455c199..09bc99a7 100644 --- a/test/kad-dht.spec.js +++ b/test/kad-dht.spec.js @@ -222,6 +222,30 @@ describe('KadDHT', () => { }) }) + it('put - get with select first', function (done) { + this.timeout(10 * 1000) + const tdht = new TestDHT() + + tdht.spawn(2, (err, dhts) => { + expect(err).to.not.exist() + const dhtA = dhts[0] + const dhtB = dhts[1] + + waterfall([ + (cb) => connect(dhtA, dhtB, cb), + (cb) => dhtA.put(Buffer.from('hello'), Buffer.from('world'), cb), + (cb) => dhtB.get(Buffer.from('hello'), { maxTimeout: 1000, selectFirst: true }, cb), + (res, cb) => { + expect(res).to.eql(Buffer.from('world')) + cb() + } + ], (err) => { + expect(err).to.not.exist() + tdht.teardown(done) + }) + }) + }) + it('provides', function (done) { this.timeout(20 * 1000)