fetching contacts is working

This commit is contained in:
slawk0
2024-11-23 20:44:58 +01:00
parent 10435af4b2
commit fc062d2983
4 changed files with 68 additions and 46 deletions

View File

@@ -1,10 +1,7 @@
import { useEffect } from 'react';
import { deleteContact, getContactsList } from '../../api/contactsApi.tsx';
import { ChatMessages } from '../../pages/Chat.tsx';
type ContactsProps = {
usernamecontact: string;
read: boolean;
};
import { ContactsProps } from '../../pages/Chat.tsx';
type ContactsListProps = {
InitializeContact: (contact: string) => void;
@@ -28,9 +25,7 @@ function ContactsList({
setContactsList((prevContacts) => {
// Check if the contact already exists in the state
if (
!prevContacts.some(
(c) => c.usernamecontact === contactsList.usernamecontact,
)
!prevContacts.some((c) => c.contact_name === contactsList.contact_name)
) {
return [...prevContacts, contactsList];
}
@@ -50,13 +45,13 @@ function ContactsList({
);
}, []);
function removeContact(usernamecontact: string) {
deleteContact(usernamecontact); // Remove contact from server
function removeContact(contact_username: string) {
deleteContact(contact_username); // Remove contact from server
setMessages([]);
// Remove contact on client
setContactsList((prevContacts) =>
prevContacts.filter(
(contact) => contact.usernamecontact !== usernamecontact,
(contact) => contact.contact_username !== contact_username,
),
);
}
@@ -71,12 +66,12 @@ function ContactsList({
<li
className="flex hover:bg-green-700 p-2 rounded cursor-pointer justify-between items-center min-h-[40px]"
onClick={() => {
InitializeContact(contact.usernamecontact);
InitializeContact(contact.contact_username);
updateContactStatus(contact, true);
}}
key={contact.usernamecontact}
key={contact.contact_id}
>
<span className="flex-shrink-0">{contact.usernamecontact}</span>
<span className="flex-shrink-0">{contact.contact_username}</span>
<div className="w-4 h-4 mx-2 flex items-center justify-center mr-auto">
<p className="text-center text-2xl text-red-200 leading-none">
@@ -87,7 +82,7 @@ function ContactsList({
<button
onClick={(e) => {
e.stopPropagation();
removeContact(contact.usernamecontact);
removeContact(contact.contact_username);
setCurrentContact(null);
localStorage.removeItem('contact');
}}

View File

@@ -18,9 +18,12 @@ export type ChatMessages = {
pending: boolean;
attachment_url: string | null;
};
type ContactsProps = {
usernamecontact: string;
export type ContactsProps = {
read: boolean;
contact_username: string;
contact_user_id: number;
contact_id: number;
};
function Chat() {

View File

@@ -105,13 +105,13 @@ async function createTables() {
CREATE TABLE IF NOT EXISTS Contacts (
contact_id SERIAL PRIMARY KEY,
sender_id INT REFERENCES Accounts(user_id) ON DELETE CASCADE,
contact_name INT REFERENCES Accounts(user_id) ON DELETE CASCADE,
receiver_id INT REFERENCES Accounts(user_id) ON DELETE CASCADE,
read BOOLEAN NOT NULL DEFAULT FALSE,
last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT unique_contact UNIQUE (sender_id, contact_name)
CONSTRAINT unique_contact UNIQUE (sender_id, receiver_id)
);
CREATE INDEX IF NOT EXISTS idx_contacts_sender_id ON Contacts (sender_id);
CREATE INDEX IF NOT EXISTS idx_contacts_contact_name ON Contacts (contact_name);
CREATE INDEX IF NOT EXISTS idx_contacts_receiver_id ON Contacts (receiver_id);
`);
console.log("Contacts table created successfully.");
} catch (e) {
@@ -347,35 +347,55 @@ async function insertContact(sender_id, receiverUsername, read) {
`insertContact sender_id: ${sender_id}, receiverUsername: ${receiverUsername}, read: ${read}`,
);
const contact_name = await getUserId(receiverUsername);
const receiver_id = await getUserId(receiverUsername);
const query = `
INSERT INTO Contacts (sender_id, contact_name, last_active, read)
INSERT INTO Contacts (sender_id, receiver_id, last_active, read)
VALUES ($1, $2, $3, $4)
ON CONFLICT ON CONSTRAINT unique_contact
DO NOTHING;
`;
try {
await client.query(query, [sender_id, contact_name, timestamp, read]);
const result = await client.query(query, [
sender_id,
receiver_id,
timestamp,
read,
]);
// if (result.rowCount === 0) {
// throw new Error("Failed to insert contact");
// }
} catch (e) {
console.error("Failed to insert contact ", e);
throw e;
}
}
async function getContacts(user_id) {
//TODO ujednolicic te contact_id contact_user_id bo w bazie sa tabele z innymi nazwami a zwraca co innego
const query = `
SELECT
c.contact_name,
c.read,
c.last_active,
a.username as receiver_username
FROM Contacts c
JOIN Accounts a ON c.contact_name = a.user_id
WHERE c.sender_id = $1
ORDER BY c.last_active DESC;
`;
SELECT
c.contact_id,
CASE
WHEN c.sender_id = $1 THEN c.receiver_id
ELSE c.sender_id
END AS contact_user_id,
a.username as contact_username, -- Added username
c.read,
c.last_active
FROM Contacts c
JOIN Accounts a ON (
CASE
WHEN c.sender_id = $1 THEN a.user_id = c.receiver_id
ELSE a.user_id = c.sender_id
END
)
WHERE c.sender_id = $1 OR c.receiver_id = $1
ORDER BY c.last_active DESC; -- Added ordering
`;
try {
const result = await client.query(query, [user_id]);
console.log("getcontacts: ", result.rows);
return result.rows;
} catch (e) {
console.error("Failed to get contacts ", e);
@@ -383,18 +403,18 @@ async function getContacts(user_id) {
}
}
async function deleteContact(user_id, contact_name) {
async function deleteContact(user_id, receiver_id) {
const query = `
DELETE FROM Contacts
WHERE sender_id = $1 AND contact_name = $2
WHERE sender_id = $1 AND receiver_id = $2
RETURNING *;
`;
try {
const result = await client.query(query, [user_id, contact_name]);
const result = await client.query(query, [user_id, receiver_id]);
if (result.rowCount === 0) {
console.log("No matching contact found with:", {
user_id,
contact_name,
receiver_id,
});
} else {
console.log("Successfully deleted contact");
@@ -404,29 +424,29 @@ async function deleteContact(user_id, contact_name) {
}
}
async function updateContactStatus(user_id, contact_name, read) {
async function updateContactStatus(user_id, receiver_id, read) {
const query = `
UPDATE Contacts SET read = $1
WHERE sender_id = $2 AND contact_name = $3;
WHERE sender_id = $2 AND receiver_id = $3;
`;
try {
await client.query(query, [read, user_id, contact_name]);
await updateContactLastActive(user_id, contact_name);
await client.query(query, [read, user_id, receiver_id]);
await updateContactLastActive(user_id, receiver_id);
console.log("Successfully updated contact status");
} catch (e) {
console.error("Failed to update contact status ", e);
}
}
async function updateContactLastActive(user_id, contact_name) {
async function updateContactLastActive(user_id, receiver_id) {
const timestamp = getTime();
const query = `
UPDATE Contacts
SET last_active = $1
WHERE sender_id = $2 AND contact_name = $3;
WHERE sender_id = $2 AND receiver_id = $3;
`;
try {
await client.query(query, [timestamp, user_id, contact_name]);
await client.query(query, [timestamp, user_id, receiver_id]);
console.log("Successfully updated contact last active time");
} catch (e) {
console.error("Failed to update contact last active time ", e);

View File

@@ -243,9 +243,13 @@ app.post("/api/chat/contact/:contact", authorizeUser, async (req, res) => {
return res.status(400).json({ message: "Invalid username provided" });
}
await insertContact(req.user.user_id, usernameContact, true);
return res.status(200).json({ message: "Successfully inserted contact" });
try {
await insertContact(req.user.user_id, usernameContact, true);
return res.status(200).json({ message: "Successfully inserted contact" });
} catch (e) {
console.error("Failed to insert contact: ", e);
return res.status(500).json({ message: "Failed to insert contact" });
}
});
app.get("/api/chat/contacts", authorizeUser, async (req, res) => {