logout is now working

This commit is contained in:
slawk0
2024-08-24 19:06:29 +02:00
parent c281076030
commit 0fb82cb94b

View File

@@ -37,6 +37,7 @@ function initializeSocket(server) {
const username = socket.user.username;
console.log(username + ' connected');
loadInitialMessages(socket);
// chat message event
socket.on('chat message', async (msg) => {
let insertedId;
@@ -71,7 +72,6 @@ function initializeSocket(server) {
try {
const query = 'SELECT id, content, username FROM messages WHERE id > $1 ORDER BY id ASC';
const values = [socket.handshake.auth.serverOffset || 0];
const result = await db.query(query, values);
for (const row of result.rows) {
@@ -92,4 +92,22 @@ function initializeSocket(server) {
return io;
}
async function loadInitialMessages(socket) {
try {
const query = 'SELECT id, content, username FROM messages ORDER BY id DESC LIMIT 50';
const result = await db.query(query);
for (const row of result.rows.reverse()) {
socket.emit('chat message', `${row.username}: ${row.content}`, row.id);
}
// Set the server offset to the latest message id
if (result.rows.length > 0) {
socket.handshake.auth.serverOffset = result.rows[result.rows.length - 1].id;
}
} catch (e) {
console.error('Error retrieving initial messages:', e);
}
}
module.exports = { initializeSocket };