73 lines
1.8 KiB
TypeScript
73 lines
1.8 KiB
TypeScript
import {
|
|
OnGatewayConnection,
|
|
SubscribeMessage,
|
|
WebSocketGateway,
|
|
WebSocketServer,
|
|
} from '@nestjs/websockets';
|
|
import { Server, Socket } from 'socket.io';
|
|
import { SendMessageDto } from './dto/sendMessage.dto';
|
|
import { SocketService } from './socket.service';
|
|
|
|
@WebSocketGateway({
|
|
namespace: '/notification',
|
|
cors: {
|
|
origin: '*',
|
|
},
|
|
transports: ['websocket'],
|
|
path: '/notification/socket.io', // آدرس سفارشی
|
|
})
|
|
export class SocketGateway implements OnGatewayConnection {
|
|
@WebSocketServer()
|
|
server: Server;
|
|
|
|
constructor(private socketService: SocketService) {}
|
|
|
|
async handleConnection(client: Socket) {
|
|
await this.socketService.clientConnection({
|
|
client_id: client.handshake.auth.token,
|
|
socket_id: client.id,
|
|
event: 'connected',
|
|
});
|
|
client.on('disconnect', async (reason) => {
|
|
await this.socketService.clientConnection({
|
|
client_id: client.handshake.auth.token,
|
|
socket_id: client.id,
|
|
event: 'disconnected',
|
|
description: reason,
|
|
});
|
|
});
|
|
}
|
|
|
|
@SubscribeMessage('sendMessageToClients')
|
|
async handleSendMessage(sendMessageDto: SendMessageDto) {
|
|
const clients = this.getConnectedClients(sendMessageDto.clientsId);
|
|
if (clients.length === 0) {
|
|
return {
|
|
status: 0,
|
|
message: 'Failed to find the clients!',
|
|
};
|
|
}
|
|
|
|
const result = await this.socketService.sendMessageToClients(
|
|
clients,
|
|
sendMessageDto.message,
|
|
sendMessageDto.event,
|
|
);
|
|
|
|
return result;
|
|
}
|
|
|
|
getConnectedClients(clientsId: string[]): Socket[] {
|
|
const connectedClients = this.server.sockets.sockets;
|
|
const clients: Socket[] = [];
|
|
|
|
for (const client of connectedClients.values()) {
|
|
if (clientsId.includes(client.handshake.auth.token)) {
|
|
clients.push(client);
|
|
}
|
|
}
|
|
|
|
return clients;
|
|
}
|
|
}
|