44 * See the LICENSE file for licensing details
55 */
66
7- import { Logger } from '@nestjs/common'
7+ import { BeforeApplicationShutdown , Logger } from '@nestjs/common'
88import {
99 MessageBody ,
1010 OnGatewayConnection ,
@@ -26,11 +26,12 @@ import { EventChangeOnlineStatus, EventUpdateOnlineStatus, UserOnline } from './
2626import { UsersManager } from './services/users-manager.service'
2727
2828@WebSocketGateway ( )
29- export class WebSocketUsers implements OnGatewayInit , OnGatewayConnection , OnGatewayDisconnect {
29+ export class WebSocketUsers implements BeforeApplicationShutdown , OnGatewayInit , OnGatewayConnection , OnGatewayDisconnect {
3030 @WebSocketServer ( ) server : Server
3131 private readonly internalEventOnlineUsers = 'listOnlineUsers'
3232 private readonly logger = new Logger ( WebSocketUsers . name )
3333 private initialized = false
34+ private shuttingDown = false
3435 private readonly waitTime : number = 3000 //ms
3536 // to show local rooms : this.server.of('/').adapter.rooms
3637
@@ -41,7 +42,12 @@ export class WebSocketUsers implements OnGatewayInit, OnGatewayConnection, OnGat
4142 setTimeout ( ( ) => ( this . initialized = true ) , this . waitTime )
4243 }
4344
45+ beforeApplicationShutdown ( _signal ?: string ) {
46+ this . shuttingDown = true
47+ }
48+
4449 async handleConnection ( socket : AuthenticatedSocketIO ) : Promise < void > {
50+ if ( this . shuttingDown ) return
4551 socket . join ( `${ USER_ROOM_PREFIX } ${ socket . user . id } ` )
4652 this . sendOnlineUser ( socket . user , parseInt ( ( socket . handshake . query . onlineStatus as string ) || '0' ) ) . catch ( ( e : Error ) =>
4753 this . logger . error ( `${ this . handleConnection . name } - ${ e } ` )
@@ -53,6 +59,7 @@ export class WebSocketUsers implements OnGatewayInit, OnGatewayConnection, OnGat
5359 }
5460
5561 async handleDisconnect ( socket : AuthenticatedSocketIO ) : Promise < void > {
62+ if ( this . shuttingDown ) return
5663 socket . leave ( `${ USER_ROOM_PREFIX } ${ socket . user . id } ` )
5764 this . sendOfflineUser ( socket . user . id ) . catch ( ( e : Error ) => this . logger . error ( `${ this . handleDisconnect . name } - ${ e } ` ) )
5865 this . logger . log (
0 commit comments