From 660c831fb12f034dd33bfb1073c1f3ea09abf3e2 Mon Sep 17 00:00:00 2001 From: farooqpk Date: Sun, 23 Jun 2024 16:12:32 +0530 Subject: [PATCH] bug fix in socket handler --- src/controllers/chat/chatList.ts | 14 ++--- src/controllers/chat/getChatKey.ts | 18 +++--- src/controllers/chat/messageList.ts | 14 ++--- src/socket/handlers/delete-msg.ts | 27 ++++----- src/socket/handlers/exit-group.ts | 31 +++++++---- src/socket/handlers/group-created.ts | 9 ++- src/socket/handlers/is-not-typing.ts | 20 +++---- src/socket/handlers/is-online.ts | 11 ++-- src/socket/handlers/is-typing.ts | 19 ++++--- src/socket/handlers/join-group.ts | 17 +++--- src/socket/handlers/leave-group.ts | 13 ++++- src/socket/handlers/send-group-msg.ts | 20 +++---- src/socket/handlers/send-private-msg.ts | 57 ++++++++++--------- src/socket/handlers/update-group-details.ts | 15 +++-- src/socket/index.ts | 61 ++++++++++++++++----- src/types/common.ts | 9 ++- src/utils/configureSocketIO.ts | 12 +--- 17 files changed, 208 insertions(+), 159 deletions(-) diff --git a/src/controllers/chat/chatList.ts b/src/controllers/chat/chatList.ts index 62f93af..019eb6d 100644 --- a/src/controllers/chat/chatList.ts +++ b/src/controllers/chat/chatList.ts @@ -4,8 +4,8 @@ import { getDataFromRedis, setDataInRedis } from "../../redis/index"; export const chatList = async (req: Request, res: Response) => { try { - // const cachedChats = await getDataFromRedis(`chats:${req.userId}`); - // if (cachedChats) return res.status(200).json(cachedChats); + const cachedChats = await getDataFromRedis(`chats:${req.userId}`); + if (cachedChats) return res.status(200).json(cachedChats); const chats = await prisma.chat.findMany({ where: { @@ -63,11 +63,11 @@ export const chatList = async (req: Request, res: Response) => { ); }); - // await setDataInRedis({ - // key: `chats:${req.userId}`, - // data: chats, - // expirationTimeInSeconds: 4 * 60 * 60, - // }); + await setDataInRedis({ + key: `chats:${req.userId}`, + data: chats, + expirationTimeInSeconds: 4 * 60 * 60, + }); res.status(200).json(chats); } catch (error) { res.status(500).json({ diff --git a/src/controllers/chat/getChatKey.ts b/src/controllers/chat/getChatKey.ts index b14ee93..c5b071a 100644 --- a/src/controllers/chat/getChatKey.ts +++ b/src/controllers/chat/getChatKey.ts @@ -6,10 +6,10 @@ export const getChatKey = async (req: Request, res: Response) => { try { const chatId = req.params.chatId; - // const cachedChatKey = await getDataFromRedis( - // `chatKey:${req.userId}:${chatId}` - // ); - // if (cachedChatKey) return res.status(200).json(cachedChatKey); + const cachedChatKey = await getDataFromRedis( + `chatKey:${req.userId}:${chatId}` + ); + if (cachedChatKey) return res.status(200).json(cachedChatKey); const chatKey = await prisma.chatKey.findFirst({ where: { @@ -21,11 +21,11 @@ export const getChatKey = async (req: Request, res: Response) => { }, }); - // await setDataInRedis({ - // key: `chatKey:${req.userId}:${chatId}`, - // data: chatKey?.encryptedKey, - // expirationTimeInSeconds: 8 * 60 * 60, - // }); + await setDataInRedis({ + key: `chatKey:${req.userId}:${chatId}`, + data: chatKey?.encryptedKey, + expirationTimeInSeconds: 8 * 60 * 60, + }); res.status(200).send(chatKey?.encryptedKey); } catch (error) { diff --git a/src/controllers/chat/messageList.ts b/src/controllers/chat/messageList.ts index 752339c..7657466 100644 --- a/src/controllers/chat/messageList.ts +++ b/src/controllers/chat/messageList.ts @@ -6,8 +6,8 @@ export const messageList = async (req: Request, res: Response) => { try { const chatId = req.params.chatId; - // const cachedMessages = await getDataFromRedis(`messages:${chatId}`); - // if (cachedMessages) return res.status(200).json(cachedMessages); + const cachedMessages = await getDataFromRedis(`messages:${chatId}`); + if (cachedMessages) return res.status(200).json(cachedMessages); const messages = await prisma.message.findMany({ where: { @@ -33,11 +33,11 @@ export const messageList = async (req: Request, res: Response) => { }, }); - // await setDataInRedis({ - // key: `messages:${chatId}`, - // data: processedMessages, - // expirationTimeInSeconds: 4 * 60 * 60, - // }); + await setDataInRedis({ + key: `messages:${chatId}`, + data: messages, + expirationTimeInSeconds: 4 * 60 * 60, + }); res.status(200).json(messages); } catch (error) { diff --git a/src/socket/handlers/delete-msg.ts b/src/socket/handlers/delete-msg.ts index f178a26..9e5d8ab 100644 --- a/src/socket/handlers/delete-msg.ts +++ b/src/socket/handlers/delete-msg.ts @@ -1,10 +1,6 @@ import { SocketEvents } from "../../events"; import { clearFromRedis, getDataFromRedis } from "../../redis"; -import { - IO_SERVER, - SOCKET, - SOCKET_PAYLOAD, -} from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; import { prisma } from "../../utils/prisma"; type DeleteMsgType = { @@ -14,12 +10,10 @@ type DeleteMsgType = { isGroup?: boolean; }; -export const deleteMsgHandler = async ({ - messageId, - recipientId, - groupId, - isGroup, -}: DeleteMsgType) => { +export const deleteMsgHandler = async ( + { io, payload, socket }: SocketHandlerParams, + { messageId, recipientId, groupId, isGroup }: DeleteMsgType +) => { if ((isGroup && !groupId) || (!isGroup && !recipientId)) return; const msg = await prisma.message.findUnique({ @@ -42,7 +36,7 @@ export const deleteMsgHandler = async ({ }, }); - if (msg?.senderId !== SOCKET_PAYLOAD.userId) return; + if (msg?.senderId !== payload.userId) return; await prisma.message.update({ where: { @@ -65,12 +59,13 @@ export const deleteMsgHandler = async ({ ]); if (isGroup) { - IO_SERVER.to(groupId!).emit(SocketEvents.DELETE_MESSAGE, messageId); + io.to(groupId!).emit(SocketEvents.DELETE_MESSAGE, messageId); } else { const recipentSocketId = await getDataFromRedis(`socket:${recipientId}`); - IO_SERVER.to( - recipentSocketId ? [recipentSocketId, SOCKET.id] : [SOCKET.id] - ).emit(SocketEvents.DELETE_MESSAGE, messageId); + io.to(recipentSocketId ? [recipentSocketId, socket.id] : [socket.id]).emit( + SocketEvents.DELETE_MESSAGE, + messageId + ); } }; diff --git a/src/socket/handlers/exit-group.ts b/src/socket/handlers/exit-group.ts index 5da2c06..abb61d7 100644 --- a/src/socket/handlers/exit-group.ts +++ b/src/socket/handlers/exit-group.ts @@ -1,16 +1,23 @@ import { SocketEvents } from "../../events"; import { clearFromRedis } from "../../redis"; -import { IO_SERVER, SOCKET_PAYLOAD } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; import { prisma } from "../../utils/prisma"; -export const exitGroupHandler = async ({ groupId }: { groupId: string }) => { +type ExitGroup = { + groupId: string; +}; + +export const exitGroupHandler = async ( + { io, payload, socket }: SocketHandlerParams, + { groupId }: ExitGroup +) => { const group = await prisma.group.findUnique({ where: { groupId, Chat: { participants: { some: { - userId: SOCKET_PAYLOAD.userId, + userId: payload.userId, }, }, }, @@ -26,7 +33,7 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => { }, ChatKey: { where: { - userId: SOCKET_PAYLOAD.userId, + userId: payload.userId, }, select: { id: true, @@ -38,7 +45,7 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => { }); const groupMembers = group?.Chat.participants; - const isExitByAdmin = group?.adminId === SOCKET_PAYLOAD.userId; + const isExitByAdmin = group?.adminId === payload.userId; const chatId = group?.chatId; await prisma.$transaction( @@ -82,7 +89,7 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => { participants: { delete: { participantId: groupMembers?.find( - (item) => item.userId === SOCKET_PAYLOAD.userId + (item) => item.userId === payload.userId )?.participantId, }, }, @@ -93,7 +100,7 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => { }, messages: { deleteMany: { - senderId: SOCKET_PAYLOAD.userId, + senderId: payload.userId, }, }, }, @@ -127,21 +134,21 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => { ] : [ clearFromRedis({ - key: `chats:${SOCKET_PAYLOAD.userId}`, + key: `chats:${payload.userId}`, }), clearFromRedis({ key: [ `messages:${group?.chatId}`, - `group:${groupId}:${SOCKET_PAYLOAD.userId}`, - `chatKey:${SOCKET_PAYLOAD.userId}:${chatId}`, + `group:${groupId}:${payload.userId}`, + `chatKey:${payload.userId}:${chatId}`, ], }), ] ); - IO_SERVER.to(groupId).emit(SocketEvents.EXIT_GROUP, { + io.to(groupId).emit(SocketEvents.EXIT_GROUP, { groupId, isExitByAdmin, - exitedUserId: SOCKET_PAYLOAD.userId, + exitedUserId: payload.userId, }); }; diff --git a/src/socket/handlers/group-created.ts b/src/socket/handlers/group-created.ts index 1070d30..7158e81 100644 --- a/src/socket/handlers/group-created.ts +++ b/src/socket/handlers/group-created.ts @@ -1,8 +1,11 @@ import { AppEvents } from "../../events"; import { getDataFromRedis } from "../../redis"; -import { IO_SERVER } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; -export const groupCreatedHandler = async (users: string[]) => { +export const groupCreatedHandler = async ( + { io }: SocketHandlerParams, + users: string[] +) => { let usersSocket: string[] = []; for (let i = 0; i < users.length; i++) { const socketId = await getDataFromRedis(`socket:${users[i]}`, true); @@ -10,5 +13,5 @@ export const groupCreatedHandler = async (users: string[]) => { usersSocket.push(socketId); } } - IO_SERVER.to(usersSocket).emit(AppEvents.GROUP_CREATED); + io.to(usersSocket).emit(AppEvents.GROUP_CREATED); }; diff --git a/src/socket/handlers/is-not-typing.ts b/src/socket/handlers/is-not-typing.ts index 281519e..4eb5c75 100644 --- a/src/socket/handlers/is-not-typing.ts +++ b/src/socket/handlers/is-not-typing.ts @@ -1,19 +1,19 @@ import { SocketEvents } from "../../events"; import { getDataFromRedis } from "../../redis"; -import { IO_SERVER, SOCKET_PAYLOAD } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; -export const isNotTypingHandler = async ({ - toUserId, -}: { +type Args = { toUserId: string; -}) => { +}; + +export const isNotTypingHandler = async ( + { io, payload, socket }: SocketHandlerParams, + { toUserId }: Args +) => { const socketId = await getDataFromRedis(`socket:${toUserId}`, true); - if (socketId && toUserId !== SOCKET_PAYLOAD.userId) { + if (socketId && toUserId !== payload.userId) { socketId && - IO_SERVER.to(socketId).emit( - SocketEvents.IS_NOT_TYPING, - SOCKET_PAYLOAD.userId - ); + io.to(socketId).emit(SocketEvents.IS_NOT_TYPING, payload.userId); } }; diff --git a/src/socket/handlers/is-online.ts b/src/socket/handlers/is-online.ts index 5da33d8..c7a1e53 100644 --- a/src/socket/handlers/is-online.ts +++ b/src/socket/handlers/is-online.ts @@ -1,12 +1,15 @@ import { SocketEvents } from "../../events"; import { getDataFromRedis } from "../../redis"; -import { SOCKET } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; -export const isOnlineHandler = async (userId: string) => { +export const isOnlineHandler = async ( + { socket, io, payload }: SocketHandlerParams, + userId: string +) => { const socketId = await getDataFromRedis(`socket:${userId}`, true); if (socketId) { - SOCKET.emit(SocketEvents.IS_ONLINE, "online"); + socket.emit(SocketEvents.IS_ONLINE, "online"); } else { - SOCKET.emit(SocketEvents.IS_ONLINE, "offline"); + socket.emit(SocketEvents.IS_ONLINE, "offline"); } }; diff --git a/src/socket/handlers/is-typing.ts b/src/socket/handlers/is-typing.ts index 2c730d2..7f918ba 100644 --- a/src/socket/handlers/is-typing.ts +++ b/src/socket/handlers/is-typing.ts @@ -1,15 +1,18 @@ import { SocketEvents } from "../../events"; import { getDataFromRedis } from "../../redis"; -import { IO_SERVER, SOCKET_PAYLOAD } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; -export const isTypingHandler = async ({ toUserId }: { toUserId: string }) => { +type Args = { + toUserId: string; +}; + +export const isTypingHandler = async ( + { io, payload, socket }: SocketHandlerParams, + { toUserId }: Args +) => { const socketId = await getDataFromRedis(`socket:${toUserId}`, true); - if (socketId && toUserId !== SOCKET_PAYLOAD.userId) { - socketId && - IO_SERVER.to(socketId).emit( - SocketEvents.IS_TYPING, - SOCKET_PAYLOAD.userId - ); + if (socketId && toUserId !== payload.userId) { + socketId && io.to(socketId).emit(SocketEvents.IS_TYPING, payload.userId); } }; diff --git a/src/socket/handlers/join-group.ts b/src/socket/handlers/join-group.ts index 7c152eb..1ad8f79 100644 --- a/src/socket/handlers/join-group.ts +++ b/src/socket/handlers/join-group.ts @@ -1,11 +1,14 @@ -import { SOCKET, SOCKET_PAYLOAD } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; import { prisma } from "../../utils/prisma"; -export const joinGroupHandler = async ({ - groupIds, -}: { +type JoinGroup = { groupIds: string[]; -}) => { +}; + +export const joinGroupHandler = async ( + { io, payload, socket }: SocketHandlerParams, + { groupIds }: JoinGroup +) => { const isUserExistInGroup = await prisma.group.findFirst({ where: { groupId: { @@ -14,7 +17,7 @@ export const joinGroupHandler = async ({ Chat: { participants: { some: { - userId: SOCKET_PAYLOAD.userId, + userId: payload.userId, }, }, }, @@ -22,6 +25,6 @@ export const joinGroupHandler = async ({ }); if (isUserExistInGroup) { - SOCKET.join(groupIds); + socket.join(groupIds); } }; diff --git a/src/socket/handlers/leave-group.ts b/src/socket/handlers/leave-group.ts index b8fb425..0519274 100644 --- a/src/socket/handlers/leave-group.ts +++ b/src/socket/handlers/leave-group.ts @@ -1,8 +1,15 @@ -import { SOCKET } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; -export const leaveGroupHandler = ({ groupIds }: { groupIds: string[] }) => { +type LeaveGroup = { + groupIds: string[]; +}; + +export const leaveGroupHandler = ( + { socket }: SocketHandlerParams, + { groupIds }: LeaveGroup +) => { groupIds?.forEach((id: string) => { - SOCKET.leave(id); + socket.leave(id); console.log("leaveGroup", id); }); }; diff --git a/src/socket/handlers/send-group-msg.ts b/src/socket/handlers/send-group-msg.ts index 6612de7..5d03a97 100644 --- a/src/socket/handlers/send-group-msg.ts +++ b/src/socket/handlers/send-group-msg.ts @@ -1,8 +1,8 @@ import { ContentType } from "@prisma/client"; import { prisma } from "../../utils/prisma"; -import { IO_SERVER, SOCKET_PAYLOAD } from "../../utils/configureSocketIO"; import { clearFromRedis } from "../../redis"; import { SocketEvents } from "../../events"; +import { SocketHandlerParams } from "../../types/common"; type GroupMsgType = { groupId: string; @@ -13,10 +13,10 @@ type GroupMsgType = { }; }; -export const sendGroupMsgHandler = async ({ - groupId, - message, -}: GroupMsgType) => { +export const sendGroupMsgHandler = async ( + { io, payload }: SocketHandlerParams, + { groupId, message }: GroupMsgType +) => { const { content, contentType, mediaPath } = message; const IS_IMAGE_OR_AUDIO = @@ -25,14 +25,14 @@ export const sendGroupMsgHandler = async ({ if ((!IS_IMAGE_OR_AUDIO && !content) || (IS_IMAGE_OR_AUDIO && !mediaPath)) { return; } - + const isUserExistInGroup = await prisma.group.findFirst({ where: { groupId, Chat: { participants: { some: { - userId: SOCKET_PAYLOAD.userId, + userId: payload.userId, }, }, }, @@ -56,9 +56,9 @@ export const sendGroupMsgHandler = async ({ data: { chatId: isUserExistInGroup.chatId, contentType, - content:!IS_IMAGE_OR_AUDIO ? content : null, + content: !IS_IMAGE_OR_AUDIO ? content : null, createdAt: new Date(), - senderId: SOCKET_PAYLOAD.userId, + senderId: payload.userId, }, include: { sender: { @@ -81,5 +81,5 @@ export const sendGroupMsgHandler = async ({ }), ]); - IO_SERVER.to(groupId).emit(SocketEvents.SEND_GROUP_MESSAGE, { message: msg }); + io.to(groupId).emit(SocketEvents.SEND_GROUP_MESSAGE, { message: msg }); }; diff --git a/src/socket/handlers/send-private-msg.ts b/src/socket/handlers/send-private-msg.ts index 3d635f1..adddb72 100644 --- a/src/socket/handlers/send-private-msg.ts +++ b/src/socket/handlers/send-private-msg.ts @@ -1,11 +1,6 @@ import { clearFromRedis, getDataFromRedis, setDataInRedis } from "../../redis"; -import { - IO_SERVER, - SOCKET, - SOCKET_PAYLOAD, -} from "../../utils/configureSocketIO"; import { prisma } from "../../utils/prisma"; -import { ContentType } from "../../types/common"; +import { ContentType, SocketHandlerParams } from "../../types/common"; import { SocketEvents } from "../../events"; type PrivateChatType = { @@ -18,17 +13,17 @@ type PrivateChatType = { encryptedChatKey: Array<{ userId: string; encryptedKey: string }>; }; -export const sendPrivateMsgHandler = async ({ - recipientId, - message, - encryptedChatKey, -}: PrivateChatType) => { +export const sendPrivateMsgHandler = async ( + { io, payload, socket }: SocketHandlerParams, + { recipientId, message, encryptedChatKey }: PrivateChatType +) => { const recipentSocketId = await getDataFromRedis( `socket:${recipientId}`, true ); - const users = [SOCKET_PAYLOAD.userId, recipientId]; + const users = [payload.userId, recipientId]; + const { content, contentType, mediaPath } = message; const IS_IMAGE_OR_AUDIO = contentType === ContentType.IMAGE || contentType === ContentType.AUDIO; @@ -54,12 +49,14 @@ export const sendPrivateMsgHandler = async ({ })); if (isAlreadyChatExist) { + console.log("Chat already exist"); + const msg = await prisma.message.create({ data: { content: !IS_IMAGE_OR_AUDIO ? content : null, createdAt: new Date(), chatId: isAlreadyChatExist.chatId, - senderId: SOCKET_PAYLOAD.userId, + senderId: payload.userId, contentType: message.contentType, mediaPath: IS_IMAGE_OR_AUDIO ? mediaPath : null, }, @@ -85,18 +82,19 @@ export const sendPrivateMsgHandler = async ({ // clear both chat and message cache await clearFromRedis({ key: [ - `chats:${SOCKET_PAYLOAD.userId}`, + `chats:${payload.userId}`, `chats:${recipientId}`, `messages:${isAlreadyChatExist.chatId}`, ], }); - IO_SERVER.to( - recipentSocketId ? [recipentSocketId, SOCKET.id] : [SOCKET.id] - ).emit(SocketEvents.SEND_PRIVATE_MESSAGE, { - isRefetchChatList: false, - message: msg, - }); + io.to(recipentSocketId ? [recipentSocketId, socket.id] : [socket.id]).emit( + SocketEvents.SEND_PRIVATE_MESSAGE, + { + isRefetchChatList: false, + message: msg, + } + ); } else { const chat = await prisma.chat.create({ data: { @@ -125,7 +123,7 @@ export const sendPrivateMsgHandler = async ({ content: !IS_IMAGE_OR_AUDIO ? content : null, createdAt: new Date(), chatId: chat.chatId, - senderId: SOCKET_PAYLOAD.userId, + senderId: payload.userId, contentType: message.contentType, mediaPath: IS_IMAGE_OR_AUDIO ? mediaPath : null, }, @@ -141,15 +139,16 @@ export const sendPrivateMsgHandler = async ({ // clear all the members chat cache await clearFromRedis({ - key: [`chats:${SOCKET_PAYLOAD.userId}`, `chats:${recipientId}`], + key: [`chats:${payload.userId}`, `chats:${recipientId}`], }); - IO_SERVER.to( - recipentSocketId ? [recipentSocketId, SOCKET.id] : [SOCKET.id] - ).emit(SocketEvents.SEND_PRIVATE_MESSAGE, { - isRefetchChatList: true, - // send encrypted chat keys for the initial chat, because we cant get chat key immediatly from client side from chat key api call - message: { ...msg, encryptedChatKeys: encryptedChatKey }, - }); + io.to(recipentSocketId ? [recipentSocketId, socket.id] : [socket.id]).emit( + SocketEvents.SEND_PRIVATE_MESSAGE, + { + isRefetchChatList: true, + // send encrypted chat keys for the initial chat, because we cant get chat key immediatly from client side from chat key api call + message: { ...msg, encryptedChatKeys: encryptedChatKey }, + } + ); } }; diff --git a/src/socket/handlers/update-group-details.ts b/src/socket/handlers/update-group-details.ts index 33e6e86..865ca3a 100644 --- a/src/socket/handlers/update-group-details.ts +++ b/src/socket/handlers/update-group-details.ts @@ -1,6 +1,6 @@ import { SocketEvents } from "../../events"; import { clearFromRedis } from "../../redis"; -import { IO_SERVER, SOCKET_PAYLOAD } from "../../utils/configureSocketIO"; +import { SocketHandlerParams } from "../../types/common"; import { prisma } from "../../utils/prisma"; type UpdateGroupDetailsType = { @@ -9,15 +9,14 @@ type UpdateGroupDetailsType = { description?: string; }; -export const updateGroupDetailsHandler = async ({ - groupId, - name, - description, -}: UpdateGroupDetailsType) => { +export const updateGroupDetailsHandler = async ( + { io, payload }: SocketHandlerParams, + { groupId, name, description }: UpdateGroupDetailsType +) => { const group = await prisma.group.update({ where: { groupId, - adminId: SOCKET_PAYLOAD.userId, + adminId: payload.userId, }, data: { name, @@ -51,7 +50,7 @@ export const updateGroupDetailsHandler = async ({ }), ]); - IO_SERVER.to(groupId).emit(SocketEvents.UPDATE_GROUP_DETAILS, { + io.to(groupId).emit(SocketEvents.UPDATE_GROUP_DETAILS, { groupId, name: group.name, description: group.description, diff --git a/src/socket/index.ts b/src/socket/index.ts index 9627e08..d6f55b0 100644 --- a/src/socket/index.ts +++ b/src/socket/index.ts @@ -1,6 +1,5 @@ import { eventEmitter } from "../server"; import { AppEvents, SocketEvents } from "../events"; -import { SOCKET_PAYLOAD, SOCKET } from "../utils/configureSocketIO"; import { isNotTypingHandler } from "./handlers/is-not-typing"; import { isOnlineHandler } from "./handlers/is-online"; import { isTypingHandler } from "./handlers/is-typing"; @@ -12,31 +11,63 @@ import { deleteMsgHandler } from "./handlers/delete-msg"; import { exitGroupHandler } from "./handlers/exit-group"; import { groupCreatedHandler } from "./handlers/group-created"; import { updateGroupDetailsHandler } from "./handlers/update-group-details"; +import { Server, Socket } from "socket.io"; +import { DecodedPayload } from "../types/DecodedPayload"; -export const socketHandler = () => { - console.log(`my username is ${SOCKET_PAYLOAD.username}`); +export const socketHandler = ( + socket: Socket, + io: Server, + payload: DecodedPayload +) => { + console.log(`my username is ${payload.username}`); - SOCKET.on(SocketEvents.IS_ONLINE, isOnlineHandler); + const socketParams = { + socket, + io, + payload, + }; - SOCKET.on(SocketEvents.IS_TYPING, isTypingHandler); + socket.on(SocketEvents.IS_ONLINE, (data) => + isOnlineHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.IS_NOT_TYPING, isNotTypingHandler); + socket.on(SocketEvents.IS_TYPING, (data) => + isTypingHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.SEND_PRIVATE_MESSAGE, sendPrivateMsgHandler); + socket.on(SocketEvents.IS_NOT_TYPING, (data) => + isNotTypingHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.JOIN_GROUP, joinGroupHandler); + socket.on(SocketEvents.SEND_PRIVATE_MESSAGE, (data) => + sendPrivateMsgHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.LEAVE_GROUP, leaveGroupHandler); + socket.on(SocketEvents.JOIN_GROUP, (data) => + joinGroupHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.SEND_GROUP_MESSAGE, sendGroupMsgHandler); + socket.on(SocketEvents.LEAVE_GROUP, (data) => + leaveGroupHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.DELETE_MESSAGE, deleteMsgHandler); + socket.on(SocketEvents.SEND_GROUP_MESSAGE, (data) => + sendGroupMsgHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.EXIT_GROUP, exitGroupHandler); + socket.on(SocketEvents.DELETE_MESSAGE, (data) => + deleteMsgHandler(socketParams, data) + ); - eventEmitter.on(AppEvents.GROUP_CREATED, groupCreatedHandler); + socket.on(SocketEvents.EXIT_GROUP, (data) => + exitGroupHandler(socketParams, data) + ); - SOCKET.on(SocketEvents.UPDATE_GROUP_DETAILS, updateGroupDetailsHandler); + eventEmitter.on(AppEvents.GROUP_CREATED, (data) => + groupCreatedHandler(socketParams, data) + ); - + socket.on(SocketEvents.UPDATE_GROUP_DETAILS, (data) => + updateGroupDetailsHandler(socketParams, data) + ); }; diff --git a/src/types/common.ts b/src/types/common.ts index d530137..0e976d6 100644 --- a/src/types/common.ts +++ b/src/types/common.ts @@ -1,3 +1,6 @@ +import { Server, Socket } from "socket.io"; +import { DecodedPayload } from "./DecodedPayload"; + export type EncryptedChatKey = { encryptedChatKey: Array<{ userId: string; @@ -11,4 +14,8 @@ export enum ContentType { IMAGE = "IMAGE", } - +export type SocketHandlerParams = { + socket: Socket; + io: Server; + payload: DecodedPayload; +}; diff --git a/src/utils/configureSocketIO.ts b/src/utils/configureSocketIO.ts index b3aa1ed..26a73e3 100644 --- a/src/utils/configureSocketIO.ts +++ b/src/utils/configureSocketIO.ts @@ -1,13 +1,8 @@ import { verifyJwt } from "./verifyJwt"; -import { Server, Socket } from "socket.io"; +import { Server } from "socket.io"; import { socketHandler } from "../socket"; import { clearFromRedis, setDataInRedis } from "../redis"; import { SocketEvents } from "../events"; -import { DecodedPayload } from "../types/DecodedPayload"; - -export let SOCKET: Socket; -export let IO_SERVER: Server; -export let SOCKET_PAYLOAD: DecodedPayload; export function configureSocketIO(io: Server) { io.on(SocketEvents.CONNECTION, async (socket) => { @@ -50,10 +45,7 @@ export function configureSocketIO(io: Server) { socket.broadcast.emit(SocketEvents.IS_CONNECTED, payload.userId); // Socket handler - SOCKET = socket; - IO_SERVER = io; - SOCKET_PAYLOAD = payload; - socketHandler(); + socketHandler(socket, io, payload); socket.on(SocketEvents.DISCONNECT, async () => { socket.rooms.forEach((room) => socket.leave(room));