This commit is contained in:
Amirhossein Mahmoodi
2024-07-29 16:15:53 +03:30
parent d09567d9d5
commit 5af4d291b2
5 changed files with 49 additions and 55 deletions

View File

@@ -12,49 +12,38 @@ export class SocketService {
private socketConnectionRepository: Repository<SocketConnection>,
) {}
async ClientConnection(data: ClientConnectionDto) {
async clientConnection(data: ClientConnectionDto) {
const client = this.socketConnectionRepository.create(data);
await this.socketConnectionRepository.save(client);
}
sendMessageToClients(clients: Socket[], data: any, event: string) {
return new Promise(async (resolveHandlerSend) => {
let sent: boolean = false;
try {
for (const client of clients) {
sent = await new Promise((resolveSend) => {
client
.timeout(2000)
.emit(event, JSON.stringify(data), (err: any) => {
if (err) {
resolveSend(false);
} else {
resolveSend(true);
}
});
async sendMessageToClients(
clients: Socket[],
data: any,
event: string,
): Promise<{ status: number; message: string }> {
const promises = clients.map(
(client) =>
new Promise<boolean>((resolve) => {
client.timeout(2000).emit(event, JSON.stringify(data), (err: any) => {
resolve(!err);
});
}
} catch (error) {
resolveHandlerSend({
status: 0,
message: 'Failed to send to the clients!',
});
return;
}
}),
);
if (!sent) {
resolveHandlerSend({
status: 0,
message: 'Failed to send to the clients!',
});
return;
}
const results = await Promise.all(promises);
const allSent = results.every((result) => result);
resolveHandlerSend({
status: 1,
message: 'Success in sending to the clients!',
});
});
if (!allSent) {
return {
status: 0,
message: 'Failed to send to all clients!',
};
}
return {
status: 1,
message: 'Success in sending to all clients!',
};
}
}