Created
August 1, 2025 11:26
-
-
Save davidcsejtei/fdc7adb8981561358932cfdbc8f6ade8 to your computer and use it in GitHub Desktop.
Custom socket room handling in Nest.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Injectable } from '@nestjs/common'; | |
| import { PinoLogger } from 'nestjs-pino'; | |
| import { Server, Socket } from 'socket.io'; | |
| import { RoomType } from '../../types/socket-room.types'; | |
| @Injectable() | |
| export class SocketRoomService { | |
| private socketServer: Server; | |
| constructor(private readonly logger: PinoLogger) {} | |
| setServer(server: Server) { | |
| this.socketServer = server; | |
| this.logger.debug({ | |
| msg: '[SocketRoomService] Socket.IO server reference set.', | |
| }); | |
| } | |
| getServer(): Server { | |
| if (!this.socketServer) { | |
| this.logger.debug({ | |
| msg: '[SocketRoomService] Server not initialized yet.', | |
| }); | |
| } | |
| return this.socketServer; | |
| } | |
| handleJoinRoom(client: Socket, type: RoomType, correlationId: string) { | |
| client.join(type); | |
| this.logger.debug({ | |
| msg: `Client joined a room`, | |
| clientId: client.id, | |
| roomType: type, | |
| correlationId: correlationId, | |
| }); | |
| } | |
| handleDisconnect(client: Socket) { | |
| this.logger.debug({ | |
| msg: `[SocketRoomService] Client ${client.id} disconnected.`, | |
| }); | |
| } | |
| emitToRoom(room: RoomType, event: string, payload: any) { | |
| if (!this.socketServer) { | |
| this.logger.debug({ | |
| msg: `[SocketRoomService] Cannot emit to room "${room}" — server not initialized.`, | |
| }); | |
| } | |
| this.socketServer.to(room).emit(event, payload); | |
| this.logger.debug({ | |
| msg: `[SocketRoomService] Emitted event "${event}" to room "${room}".`, | |
| }); | |
| } | |
| emitToClient(socketId: string, event: string, payload: any) { | |
| if (!this.socketServer) { | |
| this.logger.debug({ | |
| msg: `[SocketRoomService] Cannot emit to client "${socketId}" — server not initialized.`, | |
| }); | |
| } | |
| this.socketServer.to(socketId).emit(event, payload); | |
| this.logger.debug({ | |
| msg: `[SocketRoomService] Emitted event "${event}" to client "${socketId}".`, | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment