Skip to content

Commit a751b41

Browse files
authored
fix/should-subscribe-a-topic-only-once
2 parents f98c6aa + 58173e0 commit a751b41

File tree

3 files changed

+37
-8
lines changed

3 files changed

+37
-8
lines changed

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
"detect-node": "^2.0.4",
4646
"dirty-chai": "^2.0.1",
4747
"ipfs": "~0.31.5",
48-
"ipfsd-ctl": "~0.39.1"
48+
"ipfsd-ctl": "~0.39.1",
49+
"sinon": "^7.0.0"
4950
},
5051
"contributors": [
5152
"Vasco Santos <[email protected]>",

src/index.js

+18-7
Original file line numberDiff line numberDiff line change
@@ -86,17 +86,28 @@ class DatastorePubsub {
8686

8787
const stringifiedTopic = key.toString()
8888

89-
// Subscribe
90-
this._pubsub.subscribe(stringifiedTopic, this._handleSubscription, (err) => {
89+
this._pubsub.ls((err, res) => {
9190
if (err) {
92-
const errMsg = `cannot subscribe topic ${stringifiedTopic}`
91+
return callback(err)
92+
}
9393

94-
log.error(errMsg)
95-
return callback(errcode(new Error(errMsg), 'ERR_SUBSCRIBING_TOPIC'))
94+
// If already subscribed, just try to get it
95+
if (res && Array.isArray(res) && res.indexOf(stringifiedTopic) > -1) {
96+
return this._getLocal(key, callback)
9697
}
97-
log(`subscribed values for key ${stringifiedTopic}`)
9898

99-
this._getLocal(key, callback)
99+
// Subscribe
100+
this._pubsub.subscribe(stringifiedTopic, this._handleSubscription, (err) => {
101+
if (err) {
102+
const errMsg = `cannot subscribe topic ${stringifiedTopic}`
103+
104+
log.error(errMsg)
105+
return callback(errcode(new Error(errMsg), 'ERR_SUBSCRIBING_TOPIC'))
106+
}
107+
log(`subscribed values for key ${stringifiedTopic}`)
108+
109+
this._getLocal(key, callback)
110+
})
100111
})
101112
}
102113

test/index.spec.js

+17
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const chai = require('chai')
55
const dirtyChai = require('dirty-chai')
66
const expect = chai.expect
77
chai.use(dirtyChai)
8+
const sinon = require('sinon')
89

910
const isNode = require('detect-node')
1011
const parallel = require('async/parallel')
@@ -473,4 +474,20 @@ describe('datastore-pubsub', function () {
473474
})
474475
})
475476
})
477+
478+
it('should subscribe a topic only once', function (done) {
479+
const dsPubsubA = new DatastorePubsub(pubsubA, datastoreA, peerIdA, smoothValidator)
480+
481+
sinon.spy(pubsubA, 'subscribe')
482+
483+
dsPubsubA.get(key, (err) => {
484+
expect(err).to.exist() // not locally stored record
485+
dsPubsubA.get(key, (err) => {
486+
expect(err).to.exist() // not locally stored record
487+
expect(pubsubA.subscribe.calledOnce).to.equal(true)
488+
489+
done()
490+
})
491+
})
492+
})
476493
})

0 commit comments

Comments
 (0)