From 2e0ef74edfd81a32e06c7707ab3f6a22266e2ab1 Mon Sep 17 00:00:00 2001 From: slawk0 Date: Sat, 14 Sep 2024 23:59:37 +0200 Subject: [PATCH] contact is release! --- backend/socket.js | 11 +++++++++-- frontend/js/chat.js | 11 ++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/backend/socket.js b/backend/socket.js index e648172..2d576ca 100644 --- a/backend/socket.js +++ b/backend/socket.js @@ -102,12 +102,19 @@ function initializeSocket(server) { // Contacts socket socket.on('contacts', async (contactUsername) => { const username = socket.user.username; + // Update contact list in db try { - const query = ('INSERT INTO contacts (username, contact) VALUES ($1, $2)'); + const query = ` + INSERT INTO contacts (username, contact) + SELECT $1, $2 + WHERE NOT EXISTS ( + SELECT 1 FROM contacts WHERE username = $1 AND contact = $2 + ) + `; await db.query(query, [username, contactUsername]); } catch (err) { - console.error('Failed to update contacts') + console.error('Failed to update contacts ', err) socket.emit('socket error', 'Failed to update contacts (server error)') } // Get contact list from db diff --git a/frontend/js/chat.js b/frontend/js/chat.js index f6f1bb2..48fc6b8 100644 --- a/frontend/js/chat.js +++ b/frontend/js/chat.js @@ -103,9 +103,11 @@ async function initializeSocket() { // Contacts handler socket.on('contacts', (contacts) => { console.log('Received contacts: ', contacts); - for(const contact of contacts) { - addContact(contact.contact, socket) - } + // Clear contact to avoid duplicates because backend send all user contacts and add to existing so it just clear previous and display data from db + document.getElementById('contacts').innerHTML = ""; + for(const contact of contacts) { + addContact(contact.contact, socket) + } }) // If not previous messages found on backend @@ -157,6 +159,7 @@ async function initializeSocket() { messages.scrollTop = messages.scrollHeight; }); + // Create contact li and create remove contact button function addContact(contactUsername, socket) { const contact = document.createElement('li'); contact.className = 'contact-item'; @@ -197,7 +200,5 @@ async function initializeSocket() { addedContacts.delete(contactUsername); } } - - initializeSocket();