feat: add friend from settings pages

Now the user can add friend to his friends list through
the settings page
This commit is contained in:
Moon Patel
2023-10-13 00:53:52 +05:30
parent 5a0498af4d
commit ea04c7eb9d
2 changed files with 15 additions and 11 deletions
+8 -8
View File
@@ -123,25 +123,25 @@ router.post("/friends/:friendusername", checkAuth, async (req, res, next) => {
let { friendusername } = req.params;
let { userId } = req;
const user = await User.findById(userId);
if (req.user.username === friendusername)
res.json({
if (user.username === friendusername)
res.status(405).json({
error: { description: "Cannot add yourself as friend", message: "Cannot add this user as friends" },
});
let friendData = await User.findOne({ username: friendusername });
if (friendData) {
if (friendData.friends.includes(req.user._id)) {
res.json({
if (friendData.friends.includes(user._id)) {
res.status(409).json({
error: {
message: "User is already added as a friend",
description: "User is already added as a friend",
},
});
} else {
friendData.friends.push(req.user._id);
friendData.friends.push(user._id);
await friendData.save();
req.user.friends.push(friendData._id);
await req.user.save();
res.status(204).json(null);
user.friends.push(friendData._id);
await user.save();
res.status(201).json({});
}
} else {
res.status(404).json({
+7 -3
View File
@@ -10,13 +10,17 @@ const Friends = () => {
const form = useForm({ initialValues: { username: '' }, })
const addFriend = async () => {
console.log(form.values);
const response = await fetch(`${import.meta.env.VITE_BACKEND_HOST}/api/user/friends/${form.values.username}`, {
method: 'POST',
credentials: 'include'
credentials: 'include',
body: JSON.stringify({ username: form.values.username })
});
const resData = await response.json();
if (resData.success === false) {
if (!response.ok) {
const resData = await response.json();
form.setErrors({ username: resData.error.message })
} else {
console.log("Friend added");
}
}