refactor(realtime): extract user event "disconnect" to ClientSocket

1. extract user event "disconnect" to ClientSocket
2. add test case

Signed-off-by: BoHong Li <a60814billy@gmail.com>
This commit is contained in:
BoHong Li 2019-05-03 19:08:33 +08:00
parent 48cebc0ccc
commit 8171860d47
No known key found for this signature in database
GPG Key ID: 9696D5590D58290F
2 changed files with 31 additions and 7 deletions

View File

@ -763,6 +763,10 @@ class SocketClient {
this.socket.on('refresh', this.refreshEventHandler.bind(this)) this.socket.on('refresh', this.refreshEventHandler.bind(this))
// received user status // received user status
this.socket.on('user status', this.userStatusEventHandler.bind(this)) this.socket.on('user status', this.userStatusEventHandler.bind(this))
// when a new client disconnect
this.socket.on('disconnect', this.disconnectEventHandler.bind(this))
} }
refreshEventHandler () { refreshEventHandler () {
@ -781,6 +785,12 @@ class SocketClient {
} }
exports.emitUserStatus(this.socket) exports.emitUserStatus(this.socket)
} }
disconnectEventHandler () {
if (isDuplicatedInSocketQueue(disconnectSocketQueue, this.socket)) return
disconnectSocketQueue.push(this.socket)
exports.disconnect(this.socket)
}
} }
function connection (socket) { function connection (socket) {
@ -983,13 +993,6 @@ function connection (socket) {
} }
socket.broadcast.to(noteId).emit('cursor blur', out) 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 exports = module.exports = realtime
@ -1003,5 +1006,7 @@ exports.updateUserData = updateUserData
exports.startConnection = startConnection exports.startConnection = startConnection
exports.emitRefresh = emitRefresh exports.emitRefresh = emitRefresh
exports.emitUserStatus = emitUserStatus exports.emitUserStatus = emitUserStatus
exports.disconnect = disconnect
exports.notes = notes exports.notes = notes
exports.users = users exports.users = users
exports.disconnectSocketQueue = disconnectSocketQueue

View File

@ -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)
})
})
}) })
}) })