implementation of module and service socket

This commit is contained in:
AmirHossein Mahmoodi
2023-10-29 14:02:33 +03:30
parent a437a73c26
commit 67bb743a9e
11 changed files with 86 additions and 55 deletions

View File

@@ -1,6 +1,8 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { SocketModel } from "./models/socket.model";
import { SocketModel } from "./socket.model";
import { Server } from "socket.io";
import { NotificationInterface } from "../notifications/notification.interface";
@Injectable()
export class SocketService {
@@ -10,7 +12,42 @@ export class SocketService {
) {
}
ClientConnection(data) {
ClientConnection(data: any) {
this.socketModel.create(data);
}
sendNotificationToClients(server: Server, notificationData: NotificationInterface) {
return new Promise(async (resolveHandlerSend) => {
const connectedClients = server.sockets.sockets;
if (connectedClients.size === 0) {
resolveHandlerSend({ status: 404, 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) {
sent = await new Promise((resolveSend) => {
connectedClient[1].timeout(2000).emit("answer", JSON.stringify(notificationData), (err: any) => {
if (err) {
resolveSend(false);
} else {
resolveSend(true);
}
});
});
}
}
if (!sent) {
resolveHandlerSend({ status: 404, message: "Failed to send to the clients!" });
return;
}
resolveHandlerSend({ status: 200, message: "Success in sending to the clients!" });
});
}
}