Question about WebSocketGateway class - Emit to specific room from external component
See original GitHub issueHi,
I have a WebSocketGateway :
import { Injectable, UseFilters, UseGuards } from ‘@nestjs/common’; import { OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, } from ‘@nestjs/websockets’;
import { Logger } from ‘…/…/common/services’; import { WsGuard } from ‘…/…/user/guards’; import { WsExceptionFilter } from ‘…/…/common/exception-filters’; import { AuthService } from ‘…/…/user/services’;
@Injectable() @UseGuards(WsGuard) @UseFilters(WsExceptionFilter) @WebSocketGateway({namespace: ‘messages’}) export class MessagesGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { @WebSocketServer() server;
constructor(private logger: Logger, private authService: AuthService) {
}
afterInit(server) {
this.logger.warn(`After init`);
}
public async handleConnection(client): Promise<any> {
this.logger.log(`Client ${client.id} connected`);
try {
const user = await this.authService.retrieveUserFromAccessToken(client.handshake.query.auth_token);
if (user) {
client.join(user.id);
}
} catch (exception) {
this.logger.warn(`User can not be authenticated`);
}
}
public handleDisconnect(client): any {
this.logger.log(`Client ${client.id} disconnected`);
}
@SubscribeMessage('save')
onEvent(client, message: any): WsResponse<any> {
message.time = new Date();
this.server.in('1').emit('notifications', {text: 'You have a new message', subject: message});
client.broadcast.emit('messageSaved', message);
return {event: 'messageSaved', data: message};
}
} I’m trying to send messages (emit ) to this specific room (“1” on this example) from other parts of the application (others components that can be or not inside the same module).
There is a way to do it without connecting via a socket.io client?
Thanks
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
Hi @medbejimbj, Honestly, I don’t understand. Just to clarify - in order to emit to the specific room, you have to use client instance (there is no other way)
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.