Skip to content

Commit adee937

Browse files
authored
Atomic Subscription (#3)
Currently a TCP Emitter client was able to subscribe multiple times to the same event. This commit changes this so that a TCP Emitter client can only subscribe to an event once. Closes #2
1 parent db1a5dc commit adee937

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/tcp-emitter.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,10 @@ module.exports = {
168168
? this.subscriptions[event]
169169
: this.subscriptions[event] = []
170170

171+
// Ignore subscription if TCP Emitter client is already subscribed to the
172+
// event.
173+
if (listeners.indexOf(socket) !== -1) return
174+
171175
// Finally include the TCP Emitter client in the event's list of listeners.
172176
listeners.push(socket)
173177
},

test/tcp-emitter-test.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,64 @@ describe('TCP Emitter Tests:', function () {
103103
})
104104
})
105105

106+
describe('Scenario: Subscribing multiple times to same event:', function () {
107+
describe('Given a TCP Emitter instance,', function () {
108+
/**
109+
* TCP Emitter instance.
110+
* @type {Object}
111+
*/
112+
let tcpEmitterInst = null
113+
114+
beforeEach(function () {
115+
// Create and initialize the TCP Emitter instance which the TCP Emitter
116+
// clients will be connecting to.
117+
tcpEmitterInst = Object.create(tcpEmitter)
118+
tcpEmitterInst.init()
119+
})
120+
121+
describe('with a connected TCP Emitter client,', function () {
122+
/**
123+
* TCP Emitter client.
124+
* @type {net.Socket}
125+
*/
126+
let clientInst = null
127+
128+
beforeEach(function () {
129+
// Create and setup the TCP Emitter client to work with TCP Emitter
130+
// server.
131+
clientInst = new net.Socket()
132+
tcpEmitterInst.handleSocket({})(clientInst)
133+
})
134+
135+
describe('that is subscribed to an event,', function () {
136+
/**
137+
* Event which the TCP Emitter cliens will be listening to.
138+
* @type {string}
139+
*/
140+
let event = null
141+
142+
beforeEach(function () {
143+
event = 'event-name'
144+
145+
// Subscribe the TCP Emitter client to the events.
146+
clientInst.emit('data', payloadUtils.createSubscribe({ event }))
147+
})
148+
149+
describe('when trying to re-subscribe to the same event', function () {
150+
beforeEach(function () {
151+
clientInst.emit('data', payloadUtils.createSubscribe({ event }))
152+
})
153+
154+
it('should ignore the subscription', function () {
155+
// Assert that there is only one subscription.
156+
assert.strictEqual(tcpEmitterInst.subscriptions[event].length, 1)
157+
})
158+
})
159+
})
160+
})
161+
})
162+
})
163+
106164
describe('Scenario: Removing the last listener for an event:', function () {
107165
describe('Given a TCP Emitter instance,', function () {
108166
/**

0 commit comments

Comments
 (0)