Skip to content

Commit

Permalink
bug fix in socket handler
Browse files Browse the repository at this point in the history
  • Loading branch information
farooqpk committed Jun 23, 2024
1 parent 31730c6 commit 660c831
Show file tree
Hide file tree
Showing 17 changed files with 208 additions and 159 deletions.
14 changes: 7 additions & 7 deletions src/controllers/chat/chatList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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({
Expand Down
18 changes: 9 additions & 9 deletions src/controllers/chat/getChatKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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) {
Expand Down
14 changes: 7 additions & 7 deletions src/controllers/chat/messageList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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) {
Expand Down
27 changes: 11 additions & 16 deletions src/socket/handlers/delete-msg.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -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({
Expand All @@ -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: {
Expand All @@ -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
);
}
};
31 changes: 19 additions & 12 deletions src/socket/handlers/exit-group.ts
Original file line number Diff line number Diff line change
@@ -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,
},
},
},
Expand All @@ -26,7 +33,7 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => {
},
ChatKey: {
where: {
userId: SOCKET_PAYLOAD.userId,
userId: payload.userId,
},
select: {
id: true,
Expand All @@ -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(
Expand Down Expand Up @@ -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,
},
},
Expand All @@ -93,7 +100,7 @@ export const exitGroupHandler = async ({ groupId }: { groupId: string }) => {
},
messages: {
deleteMany: {
senderId: SOCKET_PAYLOAD.userId,
senderId: payload.userId,
},
},
},
Expand Down Expand Up @@ -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,
});
};
9 changes: 6 additions & 3 deletions src/socket/handlers/group-created.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
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);
if (socketId) {
usersSocket.push(socketId);
}
}
IO_SERVER.to(usersSocket).emit(AppEvents.GROUP_CREATED);
io.to(usersSocket).emit(AppEvents.GROUP_CREATED);
};
20 changes: 10 additions & 10 deletions src/socket/handlers/is-not-typing.ts
Original file line number Diff line number Diff line change
@@ -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);
}
};
11 changes: 7 additions & 4 deletions src/socket/handlers/is-online.ts
Original file line number Diff line number Diff line change
@@ -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");
}
};
19 changes: 11 additions & 8 deletions src/socket/handlers/is-typing.ts
Original file line number Diff line number Diff line change
@@ -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);
}
};
17 changes: 10 additions & 7 deletions src/socket/handlers/join-group.ts
Original file line number Diff line number Diff line change
@@ -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: {
Expand All @@ -14,14 +17,14 @@ export const joinGroupHandler = async ({
Chat: {
participants: {
some: {
userId: SOCKET_PAYLOAD.userId,
userId: payload.userId,
},
},
},
},
});

if (isUserExistInGroup) {
SOCKET.join(groupIds);
socket.join(groupIds);
}
};
13 changes: 10 additions & 3 deletions src/socket/handlers/leave-group.ts
Original file line number Diff line number Diff line change
@@ -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);
});
};
Loading

0 comments on commit 660c831

Please sign in to comment.