This commit is contained in:
Amirhossein Mahmoodi
2024-07-29 16:03:34 +03:30
parent 0ad17d2c8c
commit d09567d9d5
19 changed files with 9443 additions and 194 deletions

View File

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