contact is release!

This commit is contained in:
slawk0
2024-09-14 23:59:37 +02:00
parent 5213509676
commit 2e0ef74edf
2 changed files with 15 additions and 7 deletions

View File

@@ -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

View File

@@ -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();