From 34440563dba9f1b8d2ddaaf799dfab6ada8842f5 Mon Sep 17 00:00:00 2001 From: slawk0 Date: Sun, 25 Aug 2024 15:34:27 +0200 Subject: [PATCH] fixed messages displaying multiple times --- README.md | 2 +- backend/socket.js | 7 ++----- frontend/js/chat.js | 2 +- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1d0f824..fc037d0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Web chat (not finished!) ======================== - +Project for hackclub arcade. Web chat application using Express.js, Socket.io, bcrypt, Postgresql, and JWT for user authentication . Selfhost: diff --git a/backend/socket.js b/backend/socket.js index 9b5872a..66a8620 100644 --- a/backend/socket.js +++ b/backend/socket.js @@ -81,7 +81,8 @@ function initializeSocket(server) { for (const row of result.rows) { if (row.username === username || row.recipient === username) { - socket.emit('chat message', { username: row.username, recipient: row.recipient, content: row.content} ); + io.to(username).to(recipient).emit('chat message', { username: newMessage.username, recipient: newMessage.recipient, content: newMessage.content }); + } } } catch (e) { @@ -100,10 +101,6 @@ function initializeSocket(server) { `; const result = await db.query(query, [username, recipient]); - // const formattedMessages = result.rows.map(row => - // `${row.username} to ${row.recipient}: ${row.content}` - // ); - if (result.rows.length > 0) { //const { username: sender, recipient: receiver, content: content, id: id } = result.rows; console.log('Sending messages:', result.rows); diff --git a/frontend/js/chat.js b/frontend/js/chat.js index 83818c2..52a146c 100644 --- a/frontend/js/chat.js +++ b/frontend/js/chat.js @@ -50,7 +50,7 @@ async function initializeSocket() { console.log('Connected to server'); }); - socket.on('chat message', (msg) => { + socket.on('chat message', (msg, serverOffset) => { console.log('Received message:', msg); const { username, content, recipient } = msg;