Skip to content

Commit

Permalink
fixed create convo issue
Browse files Browse the repository at this point in the history
  • Loading branch information
arogya01 committed Sep 9, 2024
1 parent f6c30c5 commit ad4720f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 68 deletions.
3 changes: 2 additions & 1 deletion src/modules/chat/chat.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ export const CHAT_EVENTS = {
FETCH_MESSAGES: "FETCH_MESSAGES",
CONVERSATION_CREATED: "CONVERSATION_CREATED",
MESSAGE_SENT: "MESSAGE_SENT",
ERROR:"ERROR"
ERROR:"ERROR",
USER_COUNT_UPDATE: "USER_COUNT_UPDATE",
};
113 changes: 46 additions & 67 deletions src/modules/chat/chat.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,34 @@ import { CHAT_EVENTS } from "./chat.constants";

interface MyCustomRequest extends FastifyRequest {
decodedToken: any;
query : {
query: {
id: string;
}
}

interface QueryStringType {
userId:number;
userId: number;
}

// Add a Set to store active connections
const activeConnections = new Set<WebSocket>();

export async function chatRoutes(server: FastifyInstance) {
// console.log("server", server.websocketServer);
server.get("/chat", { websocket: true }, async (connection, req:MyCustomRequest) => {
server.get("/chat", { websocket: true }, async (connection, req: MyCustomRequest) => {
const token = req.headers['sec-websocket-protocol'];
const { id } = req.query;
console.log("hitting the web-scoket", id);

console.log("hitting the web-socket", id);

if(!id){
if (!id) {
connection.socket.send(JSON.stringify({
type: CHAT_EVENTS.ERROR,
data: { error: "Invalid conversation id" }
}));
}));
connection.socket.close();
return;
}
if(!token){

if (!token) {
connection.socket.send(JSON.stringify({
type: CHAT_EVENTS.ERROR,
data: { error: "Invalid token" }
Expand All @@ -45,8 +46,8 @@ export async function chatRoutes(server: FastifyInstance) {
return;
}

req.jwt.verify(token, (err,decoded) => {
if(err){
req.jwt.verify(token, (err, decoded) => {
if (err) {
connection.socket.send(JSON.stringify({
type: CHAT_EVENTS.ERROR,
data: { error: "Invalid token" }
Expand All @@ -56,62 +57,34 @@ export async function chatRoutes(server: FastifyInstance) {
}
});

connection.socket.on("message", async (message:any) => {
try {
const data = JSON.parse(message);
// Add the connection to the Set
activeConnections.add(connection.socket);

Check failure on line 61 in src/modules/chat/chat.routes.ts

View workflow job for this annotation

GitHub Actions / build

Argument of type 'WebSocket' is not assignable to parameter of type 'WebSocket'.

console.log("data is", data);
// Broadcast the updated user count to all clients
broadcastUserCount();

connection.socket.on("message", async (message: any) => {
try {
const data = JSON.parse(message);

if (data?.type === CHAT_EVENTS.CREATE_CONVERSATION) {
console.log("data", data);
const {data: {participants, message, groupName}} = data;
const resp = await createConversation(
data.participants,
data.message,
data.groupName
participants,
message,
groupName
);
console.log("resp", resp);
// emitting back the conversation id to the client
connection.socket.send(
JSON.stringify({
type: CHAT_EVENTS.CONVERSATION_CREATED,
data: { conversationId: resp },
})
);

// create the conversation between the users yeah...
}

if (data?.type === CHAT_EVENTS.SEND_MESSAGE) {
const createdMessage = await createMessage(data.message);
connection.socket.send(
JSON.stringify({
type: CHAT_EVENTS.MESSAGE_SENT,
data: { createdMessage },
})
);
}

if (data?.type === CHAT_EVENTS.FETCH_MESSAGES) {
const messages = await fetchAllMessages(data.conversationId);

connection.socket.send(
JSON.stringify({
type: CHAT_EVENTS.FETCH_MESSAGES,
data: { messages },
})
);
}

if (data?.type === CHAT_EVENTS.FETCH_CONVERSATIONS) {
const conversations = await fetchAllConversations(data.userId);

connection.socket.send(
JSON.stringify({
type: CHAT_EVENTS.FETCH_CONVERSATIONS,
data: { conversations },
})
);
}
// ... (rest of the message handling logic)

} catch (err) {
console.log("Error parsing JSON", err);
Expand All @@ -120,23 +93,29 @@ export async function chatRoutes(server: FastifyInstance) {

connection.socket.on("close", () => {
console.log("connection closed");
// Remove the connection from the Set
activeConnections.delete(connection.socket);

Check failure on line 97 in src/modules/chat/chat.routes.ts

View workflow job for this annotation

GitHub Actions / build

Argument of type 'WebSocket' is not assignable to parameter of type 'WebSocket'.
// Broadcast the updated user count to all clients
broadcastUserCount();
});
});

server.get("/conversations/:userId", async (req, reply) => {
const { userId } = req.params as QueryStringType;
// Add a new route to get the current number of connected users
server.get("/connected-users", (req, reply) => {
reply.send({ connectedUsers: activeConnections.size });
});

if (!userId) {
reply.code(400).send({
error: "userId is required",
});
}
// ... (rest of the routes)
}

try {
const conversations = await fetchAllConversations(userId);
reply.send(conversations);
} catch (err) {
console.log("error occured in fetching messages", err);
}
// Function to broadcast the user count to all connected clients
function broadcastUserCount() {
const message = JSON.stringify({
type: CHAT_EVENTS.USER_COUNT_UPDATE,
data: { connectedUsers: activeConnections.size },
});
}

activeConnections.forEach((socket) => {
socket.send(message);
});
}

0 comments on commit ad4720f

Please sign in to comment.