update
This commit is contained in:
@@ -1,35 +1,61 @@
|
||||
import { OnGatewayConnection, SubscribeMessage, WebSocketGateway, WebSocketServer } from "@nestjs/websockets";
|
||||
import { Server, Socket } from "socket.io";
|
||||
import { NotificationInterface } from "../notifications/notification.interface";
|
||||
import { SocketService } from "./socket.service";
|
||||
import {
|
||||
OnGatewayConnection,
|
||||
SubscribeMessage,
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import { Server, Socket } from 'socket.io';
|
||||
import { SocketService } from './socket.service';
|
||||
import { SendMessageDto } from './dto/sendMessage.dto';
|
||||
|
||||
@WebSocketGateway()
|
||||
export class SocketGateway implements OnGatewayConnection {
|
||||
@WebSocketServer() server: Server;
|
||||
|
||||
constructor(
|
||||
private socketService: SocketService,
|
||||
) {
|
||||
}
|
||||
constructor(private socketService: SocketService) {}
|
||||
|
||||
handleConnection(client: Socket) {
|
||||
this.socketService.ClientConnection({
|
||||
async handleConnection(client: Socket) {
|
||||
await this.socketService.ClientConnection({
|
||||
client_id: client.handshake.auth.token,
|
||||
socket_id: client.id,
|
||||
event: "connected",
|
||||
event: 'connected',
|
||||
});
|
||||
client.on("disconnect", (reason) => {
|
||||
this.socketService.ClientConnection({
|
||||
client.on('disconnect', async (reason) => {
|
||||
await this.socketService.ClientConnection({
|
||||
client_id: client.handshake.auth.token,
|
||||
socket_id: client.id,
|
||||
event: "disconnected",
|
||||
event: 'disconnected',
|
||||
description: reason,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@SubscribeMessage("sendNotificationToClients")
|
||||
handleSendNotification(notificationData: NotificationInterface) {
|
||||
return this.socketService.sendNotificationToClients(this.server, notificationData);
|
||||
@SubscribeMessage('sendMessageToClients')
|
||||
handleSendMessage(sendMessageDto: SendMessageDto) {
|
||||
const clients = this.getConnectedClients(sendMessageDto.auth);
|
||||
if (clients.length === 0) {
|
||||
return {
|
||||
status: 0,
|
||||
message: 'Failed to find the clients!',
|
||||
};
|
||||
}
|
||||
return this.socketService.sendMessageToClients(
|
||||
clients,
|
||||
sendMessageDto.data,
|
||||
sendMessageDto.event,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getConnectedClients(auth: string[]): Socket[] {
|
||||
const connectedClients = this.server.sockets.sockets;
|
||||
|
||||
const clients = [];
|
||||
for (const connectedClient of connectedClients) {
|
||||
if (auth.includes(connectedClient[1].handshake.auth.token)) {
|
||||
clients.push(connectedClient[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return clients;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user