Skip to content

Commit

Permalink
Merge pull request #134 from agiledev-students-fall2023/fetch-friends…
Browse files Browse the repository at this point in the history
…-expense-page

Update functionality for add friends
  • Loading branch information
elaineZhang67 authored Nov 30, 2023
2 parents 25cbd76 + ebd3654 commit 4eab2de
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 27 deletions.
2 changes: 2 additions & 0 deletions back-end/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const userInfoPageRoute = require("./routes/UserInfoPageRoute");
const signupRoute = require("./routes/signupRoute");
const forgotPasswordRoute = require("./routes/forgotPasswordRoute");
const logoutRoute = require("./routes/logoutRoute");
const searchFriendRoute = require('./routes/searchFriendRoute');

// connect to the database
// console.log(`Conneting to MongoDB at ${process.env.MONGODB_URI}`)
Expand Down Expand Up @@ -55,6 +56,7 @@ app.use("/AddEventMember", addEventMemberRoute);
app.use("/signup", signupRoute);
app.use("/forgot-password", forgotPasswordRoute);
app.use("/logout", logoutRoute);
app.use("/searchFriend", searchFriendRoute);

// export the express app we created to make it available to other modules
module.exports = app;
1 change: 1 addition & 0 deletions back-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"express": "^4.18.2",
"express-validator": "^7.0.1",
"jsonwebtoken": "^9.0.2",
"jwt-decode": "^4.0.0",
"mongoose": "^8.0.1"
},
"devDependencies": {
Expand Down
42 changes: 31 additions & 11 deletions back-end/routes/addFriendRoute.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
const express = require('express');
const router = express.Router();
const { User } = require("../models/User.js");

// Hardcoded user data to simulate a database
let userData = {
"name": "Sallyanne",
"email": "[email protected]",
"phone": "764-995-4333",
"avatar": "https://robohash.org/eligendiquiased.png?size=50x50&set=set1",
}
router.post('/', async (req, res) => {
const { currentUserId, friendUserId } = req.body;

// Endpoint to get user data after search
router.get('/', (req, res) => {
res.json(userData);
try {
const currentUser = await User.findById(currentUserId);
const friendUser = await User.findById(friendUserId);

if (!currentUser || !friendUser) {
return res.status(404).send("One or both users not found");
}

if (!currentUser.friends.includes(friendUserId)) {
currentUser.friends.push(friendUserId);
await currentUser.save();
console.log(`Added ${friendUserId} to ${currentUser.id}'s friends list.`);
} else {
return res.status(200).send("Already friends");
}

if (!friendUser.friends.includes(currentUserId)) {
friendUser.friends.push(currentUserId);
await friendUser.save();
}

res.status(200).send("Friends added successfully");

} catch (error) {
console.error("Error in addFriend route:", error);
res.status(500).send("Error adding friend");
}
});

module.exports = router;
module.exports = router;
18 changes: 18 additions & 0 deletions back-end/routes/searchFriendRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const express = require("express");
const router = express.Router();
const { User } = require("../models/User.js");

router.get('/', async (req, res) => {
const { username } = req.query;
try {
const userData = await User.findOne({ username: username }).select("username avatar _id");
if (!userData) {
return res.status(404).send("User not found");
}
res.json(userData);
} catch (error) {
res.status(500).json({ message: "Error accessing the database" });
}
});

module.exports = router;
1 change: 1 addition & 0 deletions front-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.1",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.17.0",
Expand Down
74 changes: 58 additions & 16 deletions front-end/src/components/AddFriendModal.jsx
Original file line number Diff line number Diff line change
@@ -1,61 +1,103 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import addFriendButton from "../images/plus-button.png";
import { jwtDecode } from 'jwt-decode';

function AddFriendModal({ showModal, onClose }) {
const [userData, setUserData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');

const backupUserData = {
"avatar": "https://robohash.org/facerevoluptasconsequatur.png?size=50x50\u0026set=set1",
"name": "Ulberto Crow"
};

async function handleSearchClick() {
setUserData(null);
setError('');
setLoading(true);
const username = document.querySelector('.input-content').value;
try {
const response = await fetch("http://localhost:3001/addFriends");
const response = await fetch(`http://localhost:3001/searchFriend?username=${username}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
if (response.status === 404) {
setError('User not found.');
} else {
throw new Error(`HTTP error! Status: ${response.status}`);
}
} else {
const data = await response.json();
setUserData(data);
}
const data = await response.json();
setUserData(data);
} catch (error) {
console.error("Error fetching data:", error);
setError('Failed to fetch data. Please try again.');
setUserData(backupUserData); // Using the backup data on error
} finally {
setLoading(false);
}
}

function addFriend(friendUserId) {
const token = localStorage.getItem("token");
const currentUser = jwtDecode(token);

if (!currentUser || !currentUser.id) {
console.error("No current user found in local storage.");
return;
}

if (currentUser.id === friendUserId) {
setError("You cannot add yourself as a friend.");
return;
}

fetch("http://localhost:3001/addFriends", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ currentUserId: currentUser.id, friendUserId: friendUserId }),
})
.then(response => {
if (!response.ok) {
throw new Error('Could not add friend');
}
return response.text();
})
.then(message => {
setError(message);
})
.catch(error => {
console.error("Error adding friend:", error);
setError("Failed to add friend. Please try again.");
});
}


return (
<div className="modal">
<div className="modal-content">
<span className="close" onClick={onClose}>&times;</span>
<h2>Add a new friend</h2>
<input type="text" placeholder="Email or Phone" className='input-content'/>
<input type="text" placeholder="Enter username" className='input-content'/>
<button onClick={handleSearchClick}>Search</button>
{loading && <div>Loading...</div>}
{userData && (
<div className="add-friend-item">
<img src={userData.avatar} alt={`${userData.name}'s avatar`} className="friend-avatar"/>
<span className="add-friend-name">{userData.name}</span>
<img src={userData.avatar} alt={`avatar`} className="friend-avatar"/>
<span className="add-friend-name">{userData.username}</span>
<img
src={addFriendButton}
alt="Add friend"
className="add-friend-button"
style={{ width: "50px", height: "50px" }}
onClick={() => addFriend(userData._id)}
/>
</div>
)}
{error && (
<div className="error-message">
{error}
</div>
)}
</div>
</div>
);
}

export default AddFriendModal;

export default AddFriendModal;

0 comments on commit 4eab2de

Please sign in to comment.