From 8171860d4762b62aeca732c104127e69ecd133fc Mon Sep 17 00:00:00 2001 From: BoHong Li Date: Fri, 3 May 2019 19:08:33 +0800 Subject: [PATCH] refactor(realtime): extract user event "disconnect" to ClientSocket 1. extract user event "disconnect" to ClientSocket 2. add test case Signed-off-by: BoHong Li --- lib/realtime.js | 19 ++++++++++++------- test/realtime.test.js | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/lib/realtime.js b/lib/realtime.js index 9214d80f..008b92dd 100644 --- a/lib/realtime.js +++ b/lib/realtime.js @@ -763,6 +763,10 @@ class SocketClient { this.socket.on('refresh', this.refreshEventHandler.bind(this)) // received user status this.socket.on('user status', this.userStatusEventHandler.bind(this)) + + // when a new client disconnect + this.socket.on('disconnect', this.disconnectEventHandler.bind(this)) + } refreshEventHandler () { @@ -781,6 +785,12 @@ class SocketClient { } exports.emitUserStatus(this.socket) } + + disconnectEventHandler () { + if (isDuplicatedInSocketQueue(disconnectSocketQueue, this.socket)) return + disconnectSocketQueue.push(this.socket) + exports.disconnect(this.socket) + } } function connection (socket) { @@ -983,13 +993,6 @@ function connection (socket) { } socket.broadcast.to(noteId).emit('cursor blur', out) }) - - // when a new client disconnect - socket.on('disconnect', function () { - if (isDuplicatedInSocketQueue(socket, disconnectSocketQueue)) return - disconnectSocketQueue.push(socket) - disconnect(socket) - }) } exports = module.exports = realtime @@ -1003,5 +1006,7 @@ exports.updateUserData = updateUserData exports.startConnection = startConnection exports.emitRefresh = emitRefresh exports.emitUserStatus = emitUserStatus +exports.disconnect = disconnect exports.notes = notes exports.users = users +exports.disconnectSocketQueue = disconnectSocketQueue diff --git a/test/realtime.test.js b/test/realtime.test.js index ba4690f8..5fefa029 100644 --- a/test/realtime.test.js +++ b/test/realtime.test.js @@ -537,6 +537,25 @@ describe('realtime', function () { }) + describe('disconnect', function () { + it('should push socket to disconnect queue and call disconnect function', () => { + const disconnectFunc = eventFuncMap.get('disconnect') + const disconnectStub = sinon.stub(realtime, 'disconnect') + disconnectFunc() + assert(realtime.disconnectSocketQueue.length === 1) + assert(disconnectStub.calledOnce) + }) + + it('should quick return when socket is in disconnect queue', () => { + const disconnectFunc = eventFuncMap.get('disconnect') + const disconnectStub = sinon.stub(realtime, 'disconnect') + realtime.disconnectSocketQueue.push(clientSocket) + disconnectFunc() + assert(disconnectStub.called === false) + }) + + }) + }) })