moved contacts api requests to contactsApi.tsx
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1 +1,2 @@
|
||||
.idea
|
||||
.idea
|
||||
node_modules
|
||||
@@ -1,14 +1,63 @@
|
||||
import { axiosClient } from '../App.tsx';
|
||||
type ContactsProps = {
|
||||
usernamecontact: string;
|
||||
read: boolean;
|
||||
};
|
||||
|
||||
export function setStatus(contact: string, read: boolean) {
|
||||
axiosClient
|
||||
.put(
|
||||
`api/chat/contacts/${contact}`,
|
||||
type MessagesProps = {
|
||||
sender: string;
|
||||
message: string;
|
||||
recipient: string;
|
||||
message_id: number;
|
||||
timestamp: string;
|
||||
};
|
||||
export async function getContactsList(): Promise<ContactsProps[]> {
|
||||
try {
|
||||
const response = await axiosClient.get(
|
||||
'http://localhost:5173/api/chat/contacts',
|
||||
);
|
||||
console.log();
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch /api/chat/contacts: ', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
export async function setContactStatus(contact: string, read: boolean) {
|
||||
try {
|
||||
const response = await axiosClient.put(
|
||||
`/api/chat/contacts/${contact}`,
|
||||
{ status: read },
|
||||
{ withCredentials: true },
|
||||
)
|
||||
.then((res) => {
|
||||
console.log(res.data.message);
|
||||
})
|
||||
.catch((e) => console.log(e.response.data.message));
|
||||
);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
console.error('Failed to set contact status: ', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendContact(contact: string) {
|
||||
try {
|
||||
const response = await axiosClient.post(`/api/chat/contact/${contact}`);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
console.error('Failed to send contact: ', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMessages(
|
||||
contact: string | null,
|
||||
): Promise<MessagesProps[]> {
|
||||
if (contact !== null) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const response = await axiosClient.get(`/api/chat/messages/${contact}`);
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
console.error('Failed to get messages: ', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useForm, SubmitHandler } from 'react-hook-form';
|
||||
import { useEffect } from 'react';
|
||||
import { sendContact } from '../../api/contactsApi.tsx';
|
||||
|
||||
type Input = {
|
||||
contact: string;
|
||||
@@ -32,6 +33,7 @@ function ContactForm({
|
||||
|
||||
const submitContact: SubmitHandler<Input> = (data) => {
|
||||
const contact = data.contact.toLowerCase().trim();
|
||||
sendContact(contact);
|
||||
InitializeContact(contact);
|
||||
setContactsList([
|
||||
...contactsList,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { socket } from '../../socket/socket.tsx';
|
||||
import { useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { getContactsList } from '../../api/contactsApi.tsx';
|
||||
|
||||
type ContactsProps = {
|
||||
usernamecontact: string;
|
||||
read: boolean;
|
||||
lastActive: string;
|
||||
};
|
||||
|
||||
type ContactsListProps = {
|
||||
@@ -15,15 +15,6 @@ type ContactsListProps = {
|
||||
setCurrentContact: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
updateStatus: (contactObj: ContactsProps, read: true) => void;
|
||||
};
|
||||
async function getContactsList(): Promise<ContactsProps[]> {
|
||||
try {
|
||||
const response = await axios.get('http://localhost:5173/api/chat/contacts');
|
||||
return response.data;
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch /api/chat/contacts: ', e);
|
||||
return []; // or throw error if you prefer
|
||||
}
|
||||
}
|
||||
function ContactsList({
|
||||
InitializeContact,
|
||||
contactsList,
|
||||
@@ -88,7 +79,7 @@ function ContactsList({
|
||||
if (a.read !== b.read) {
|
||||
return a.read ? 1 : -1;
|
||||
}
|
||||
return new Date(b.lastActive).getTime() - new Date(a.lastActive).getTime();
|
||||
return 0;
|
||||
});
|
||||
|
||||
const addContactsList = sortedContacts.map(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react';
|
||||
import { socket } from '../../socket/socket.tsx';
|
||||
import { useOutletContext } from 'react-router-dom';
|
||||
import { UsernameType } from '../../utils/ProtectedRoutes.tsx';
|
||||
import { getMessages } from '../../api/contactsApi.tsx';
|
||||
type ChatMessages = {
|
||||
sender: string;
|
||||
message: string;
|
||||
@@ -38,6 +39,8 @@ function MessagesArea({
|
||||
return;
|
||||
}
|
||||
|
||||
getMessages(currentContact);
|
||||
|
||||
function messageHandler(msg: ChatMessages) {
|
||||
setMessages((prevMessages) => {
|
||||
// Check if the message already exists in the state
|
||||
@@ -59,6 +62,7 @@ function MessagesArea({
|
||||
messageHandler(msg);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('historical messages', (msg: ChatMessages[]) => {
|
||||
console.log('Received historical messages: ', msg);
|
||||
|
||||
|
||||
@@ -5,10 +5,9 @@ import ContactForm from '../components/chat/ContactForm.tsx';
|
||||
import MessagesArea from '../components/chat/MessagesArea.tsx';
|
||||
import { useEffect, useState } from 'react';
|
||||
import ContactsList from '../components/chat/ContactsList.tsx';
|
||||
import { initializeSocket, sendContact } from '../socket/socket.tsx';
|
||||
import { initializeSocket } from '../socket/socket.tsx';
|
||||
import Cookies from 'js-cookie';
|
||||
import { setStatus } from '../api/contactsApi.tsx';
|
||||
import { axiosClient } from '../App.tsx';
|
||||
import { getMessages, setContactStatus } from '../api/contactsApi.tsx';
|
||||
|
||||
type ChatMessages = {
|
||||
sender: string;
|
||||
@@ -20,7 +19,6 @@ type ChatMessages = {
|
||||
type ContactsProps = {
|
||||
usernamecontact: string;
|
||||
read: boolean;
|
||||
lastActive: string;
|
||||
};
|
||||
|
||||
type ContactObjProps = {
|
||||
@@ -42,30 +40,20 @@ function Chat() {
|
||||
|
||||
function InitializeContact(newContact: string) {
|
||||
setMessages([]); // Clear messages from previous contact
|
||||
//sendRequestHistoricalMessages(newContact); // Request historical messages for new contact
|
||||
localStorage.setItem('contact', newContact);
|
||||
setCurrentContact(newContact);
|
||||
sendContact({ contact: newContact, read: true });
|
||||
localStorage.setItem('contact', newContact); // Set current contact in localstorage
|
||||
setCurrentContact(newContact); // Set state for current user (used in contactProfile.tsx
|
||||
getMessages(newContact);
|
||||
setContactsList((prevContacts) =>
|
||||
prevContacts.map((c) =>
|
||||
c.usernamecontact === newContact ? { ...c, read: true } : c,
|
||||
),
|
||||
);
|
||||
axiosClient
|
||||
.put(
|
||||
`api/chat/contacts/${newContact}`,
|
||||
{ status: true },
|
||||
{ withCredentials: true },
|
||||
)
|
||||
.then((res) => {
|
||||
console.log(res.data.message);
|
||||
})
|
||||
.catch((e) => console.log(e.response.data.message));
|
||||
console.log('Contact submitted:', newContact);
|
||||
}
|
||||
setContactStatus(newContact, true);
|
||||
|
||||
console.log('Contact set up', newContact);
|
||||
}
|
||||
|
||||
function updateStatus(contactObj: ContactObjProps, read: boolean) {
|
||||
function updateContactStatus(contactObj: ContactObjProps, read: boolean) {
|
||||
setContactsList((prevContacts) =>
|
||||
prevContacts.map((contact) => {
|
||||
if (contact.usernamecontact === contactObj.usernamecontact) {
|
||||
@@ -92,7 +80,7 @@ function Chat() {
|
||||
contactsList={contactsList}
|
||||
setContactsList={setContactsList}
|
||||
setCurrentContact={setCurrentContact}
|
||||
updateStatus={updateStatus}
|
||||
updateStatus={updateContactStatus}
|
||||
/>
|
||||
<hr />
|
||||
<UserProfile />
|
||||
@@ -108,8 +96,8 @@ function Chat() {
|
||||
messages={messages}
|
||||
setMessages={setMessages}
|
||||
currentContact={currentContact}
|
||||
setStatus={setStatus}
|
||||
updateStatus={updateStatus}
|
||||
setStatus={setContactStatus}
|
||||
updateStatus={updateContactStatus}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-shrink-0 mb-2 mt-0">
|
||||
|
||||
3
package-lock.json
generated
3
package-lock.json
generated
@@ -1,9 +1,12 @@
|
||||
{
|
||||
"name": "relay",
|
||||
"version": "0.0.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "relay",
|
||||
"version": "0.0.1",
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.0.1"
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"scripts": {
|
||||
"dev": "concurrently \"npm run dev:client\" \"npm run dev:server\"",
|
||||
"dev:client": "cd client && npm run dev",
|
||||
"dev:server": "cd server && node server",
|
||||
"dev:server": "cd server && nodemon server",
|
||||
"install:all": "concurrently \"npm install\" \"cd client && npm install\" \"cd server && npm install\"",
|
||||
"build": "concurrently \"cd client && npm run build\" \"cd server && node server.js\""
|
||||
},
|
||||
|
||||
@@ -166,20 +166,29 @@ app.post("/api/chat/contact/:contact", authorizeUser, async (req, res) => {
|
||||
return res.status(400).json({ message: "Missing contact parameter" });
|
||||
}
|
||||
const usernameContact = filter(req.params.contact);
|
||||
await insertContact(req.user.username, usernameContact);
|
||||
await insertContact(req.user.username, usernameContact, true);
|
||||
|
||||
return res.status(200).json({ message: "Successfully inserted contact" });
|
||||
});
|
||||
|
||||
app.get("/api/chat/contacts", authorizeUser, async (req, res) => {
|
||||
if (!req.user.username) {
|
||||
return res.status(401).json({
|
||||
message: "Missing username (that's weird you shouldn't see that)",
|
||||
});
|
||||
}
|
||||
const contacts = await getContacts(req.user.username);
|
||||
console.log("Sent contacts list for: ", req.user.username);
|
||||
return res.status(200).json(contacts);
|
||||
});
|
||||
|
||||
app.get("/api/chat/messages", authorizeUser, async (req, res) => {
|
||||
const messages = await getMessages(req.user.username);
|
||||
console.log("Sent contacts list for: ", req.user.username);
|
||||
app.get("/api/chat/messages/:contact", authorizeUser, async (req, res) => {
|
||||
if (!req.params.contact) {
|
||||
return res.status(400).json({ message: "Missing contact parameter" });
|
||||
}
|
||||
|
||||
const messages = await getMessages(req.user.username, req.params.contact);
|
||||
console.log("Sent messages for: ", req.user.username, "messages: ", messages);
|
||||
return res.status(200).json(messages);
|
||||
});
|
||||
|
||||
|
||||
@@ -84,11 +84,6 @@ function initializeSocket(io) {
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("historical messages", async (recipient) => {
|
||||
const messages = await getMessages(username, recipient.recipient);
|
||||
io.to(username).emit("historical messages", messages);
|
||||
});
|
||||
|
||||
socket.on("add contact", (contactInf) => {
|
||||
let { contact, read } = contactInf;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user