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,53 +1,60 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { SocketModel } from "./socket.model";
import { Server } from "socket.io";
import { NotificationInterface } from "../notifications/notification.interface";
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Socket } from 'socket.io';
import { Repository } from 'typeorm';
import { ClientConnectionDto } from './dto/clientConnection.dto';
import { SocketConnection } from './socket.entity';
@Injectable()
export class SocketService {
constructor(
@InjectModel(SocketModel)
private socketModel: typeof SocketModel,
) {
@InjectRepository(SocketConnection)
private socketConnectionRepository: Repository<SocketConnection>,
) {}
async ClientConnection(data: ClientConnectionDto) {
const client = this.socketConnectionRepository.create(data);
await this.socketConnectionRepository.save(client);
}
ClientConnection(data: any) {
this.socketModel.create(data);
}
sendNotificationToClients(server: Server, notificationData: NotificationInterface) {
sendMessageToClients(clients: Socket[], data: any, event: string) {
return new Promise(async (resolveHandlerSend) => {
const connectedClients = server.sockets.sockets;
let sent: boolean = false;
if (connectedClients.size === 0) {
resolveHandlerSend({ status: 1, message: "Failed to find the clients!" });
return;
}
let sent: any = false;
for (const connectedClient of connectedClients) {
if (connectedClient[1].handshake.auth.token == notificationData.telephone_id) {
try {
for (const client of clients) {
sent = await new Promise((resolveSend) => {
connectedClient[1].timeout(2000).emit("answer", JSON.stringify(notificationData), (err: any) => {
if (err) {
resolveSend(false);
} else {
resolveSend(true);
}
});
client
.timeout(2000)
.emit(event, JSON.stringify(data), (err: any) => {
if (err) {
resolveSend(false);
} else {
resolveSend(true);
}
});
});
}
} catch (error) {
resolveHandlerSend({
status: 0,
message: 'Failed to send to the clients!',
});
return;
}
if (!sent) {
resolveHandlerSend({ status: 2, message: "Failed to send to the clients!" });
resolveHandlerSend({
status: 0,
message: 'Failed to send to the clients!',
});
return;
}
resolveHandlerSend({ status: 0, message: "Success in sending to the clients!" });
resolveHandlerSend({
status: 1,
message: 'Success in sending to the clients!',
});
});
}
}