init notification
This commit is contained in:
61
src/socket/socket.gateway.ts
Normal file
61
src/socket/socket.gateway.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { OnGatewayConnection, SubscribeMessage, WebSocketGateway, WebSocketServer } from "@nestjs/websockets";
|
||||
import { Server, Socket } from "socket.io";
|
||||
import { NotificationInterface } from "../notifications/interfaces/notification.interface";
|
||||
import { SocketService } from "./socket.service";
|
||||
|
||||
@WebSocketGateway()
|
||||
export class SocketGateway implements OnGatewayConnection {
|
||||
@WebSocketServer() server: Server;
|
||||
|
||||
constructor(
|
||||
private socketService: SocketService,
|
||||
) {
|
||||
}
|
||||
|
||||
handleConnection(client: Socket) {
|
||||
this.socketService.ClientConnection({
|
||||
client_id: client.handshake.auth.token,
|
||||
socket_id: client.id,
|
||||
event: "connected",
|
||||
});
|
||||
client.on("disconnect", (reason) => {
|
||||
this.socketService.ClientConnection({
|
||||
client_id: client.handshake.auth.token,
|
||||
socket_id: client.id,
|
||||
event: "disconnected",
|
||||
description: reason,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@SubscribeMessage("sendNotificationToClients")
|
||||
handleSendNotification(notificationData: NotificationInterface) {
|
||||
return new Promise(async (resolve) => {
|
||||
const connectedClients = this.server.sockets.sockets;
|
||||
|
||||
if (connectedClients.size === 0) resolve({ status: "failed", message: "Clients not found!" });
|
||||
|
||||
let sent: any = false;
|
||||
|
||||
for (const connectedClient of connectedClients) {
|
||||
if (connectedClient[1].handshake.auth.token == notificationData.telephone_id) {
|
||||
sent = await new Promise((resolve) => {
|
||||
connectedClient[1].timeout(2000).emit("answer", JSON.stringify(notificationData), (err: any) => {
|
||||
if (err) {
|
||||
resolve(false);
|
||||
} else {
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (sent) {
|
||||
resolve({ status: "success", message: "Sent to clients" });
|
||||
} else {
|
||||
resolve({ status: "failed", message: "Not sent to clients" });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user