Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Added favorite/unfavorite status for user and removed local storage for favorite feature successfully issue 497 #507

Merged
merged 1 commit into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions backend/src/routes/post/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,41 @@ export const getFavoritePostsController = async (req: UserAuthRequest, res: Resp
}
};

export const checkFavoriteStatusController = async (req: UserAuthRequest, res: Response) => {
try {
const userId = req.userId;
const postId = req.params.id;

if (!userId) {
return res.status(400).json({ error: "User ID is required." });
}

const user = await prisma.user.findFirst({
where: { id: userId },
select: { verified: true }
});

if (!user?.verified) {
return res.status(403).json({ error: "User is not verified!" });
}

const favorite = await prisma.favorite.findUnique({
where: {
userId_postId: {
userId,
postId
}
}
});

const isFavorite = favorite ? true : false;

res.status(200).json({ isFavorite });
} catch (error) {
res.status(500).json({ error: "Failed to check favorite status." });
}
};

export const getLeaderboardController = async (req: Request, res: Response) => {
try {
const leaderboard = await prisma.user.findMany({
Expand Down
4 changes: 3 additions & 1 deletion backend/src/routes/post/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Router } from "express";
import authMiddleware from "../../middleware/auth"

import { aiCustomization, createCommentController, createPostController, deletePostController, favoritePostController, getAllTagsController, getCommentsController, getFavoritePostsController, getLeaderboardController, getPostController, getPostReactionsController, getPostsWithPagination, getUserReactionController, reactToPostController, removeReactionController, unfavoritePostController, updatePostController } from "./controller";
import { checkFavoriteStatusController,aiCustomization, createCommentController, createPostController, deletePostController, favoritePostController, getAllTagsController, getCommentsController, getFavoritePostsController, getLeaderboardController, getPostController, getPostReactionsController, getPostsWithPagination, getUserReactionController, reactToPostController, removeReactionController, unfavoritePostController, updatePostController } from "./controller";

const postRouter = Router();

Expand All @@ -25,6 +25,8 @@ postRouter.post('/:id/unfavorite', authMiddleware, unfavoritePostController);

postRouter.get('/:id/favorites', authMiddleware, getFavoritePostsController);

postRouter.get('/:id/favorite-status', authMiddleware, checkFavoriteStatusController);

postRouter.get('/all/leaderboard', getLeaderboardController);

postRouter.delete('/delete/:id', authMiddleware, deletePostController);
Expand Down
49 changes: 26 additions & 23 deletions frontend/src/components/PostCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,24 @@ const PostCard = ({ post, onDelete, currentUser }: Props) => {
}, [post.id]);

useEffect(() => {
const favoriteStatus = localStorage.getItem(`post-${post.id}-favorite`);
setIsFavorite(favoriteStatus === "true");
const fetchFavoriteStatus = async () => {
try {
const token = localStorage.getItem("token");
if (!token) {
return;
}
const { data } = await axios.get(`/api/v1/posts/${post.id}/favorite-status`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
setIsFavorite(data.isFavorite);
} catch (error) {
toast.error("Failed to fetch favorite status");
}
};

fetchFavoriteStatus();
}, [post.id]);

const handleAddToFavorite = async () => {
Expand All @@ -61,18 +77,11 @@ const PostCard = ({ post, onDelete, currentUser }: Props) => {
}
);
setIsFavorite(true);
localStorage.setItem(`post-${post.id}-favorite`, "true");
toast.success("Post added to favorites");
} catch (e) {
const error = e as AxiosError<{
error: {
message: string;
};
}>;
const error = e as AxiosError<{ error: { message: string } }>;
if (error.response && error.response.status === 403) {
toast.error(
error.response.data.error.message || "User is not verified!"
);
toast.error(error.response.data.error.message || "User is not verified!");
} else {
toast.error("Failed to add to favorites. Please try again later.");
}
Expand All @@ -96,18 +105,11 @@ const PostCard = ({ post, onDelete, currentUser }: Props) => {
}
);
setIsFavorite(false);
localStorage.removeItem(`post-${post.id}-favorite`);
toast.success("Post removed from favorites");
} catch (e) {
const error = e as AxiosError<{
error: {
message: string;
};
}>;
const error = e as AxiosError<{ error: { message: string } }>;
if (error.response && error.response.status === 403) {
toast.error(
error.response.data.error.message || "User is not verified!"
);
toast.error(error.response.data.error.message || "User is not verified!");
} else {
toast.error("Failed to remove from favorites. Please try again later.");
}
Expand All @@ -117,7 +119,7 @@ const PostCard = ({ post, onDelete, currentUser }: Props) => {
const handleDelete = async () => {
setIsDeleting(true);
try {
const token = localStorage.getItem('token');
const token = localStorage.getItem("token");
if (!token) {
toast.error('Please login to delete post');
return;
Expand Down Expand Up @@ -197,7 +199,8 @@ const PostCard = ({ post, onDelete, currentUser }: Props) => {
className="cursor-pointer text-[#e74e4e] dark:text-white"
/>
)}
</div> <p className="text-[#000435] bg-white dark:text-white dark:bg-blue-950 mb-4">
</div>
<p className="text-[#000435] bg-white dark:text-white dark:bg-blue-950 mb-4">
{post.description.length > 100
? `${post.description.slice(0, 100)}...`
: post.description}
Expand Down Expand Up @@ -250,4 +253,4 @@ const PostCard = ({ post, onDelete, currentUser }: Props) => {
);
};

export default PostCard;
export default PostCard;
Loading