Skip to content

Commit

Permalink
Add delete for comment and post along with transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
tanish35 committed Oct 15, 2024
1 parent 4748e44 commit c986d7f
Show file tree
Hide file tree
Showing 3 changed files with 155 additions and 7 deletions.
22 changes: 21 additions & 1 deletion backend/src/controllers/postController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ const fetchSinglePost = asyncHandler(async (req: Request, res: Response) => {
},
User: {
select: {
user_id: true,
username: true,
pic: true,
},
Expand All @@ -231,6 +232,7 @@ const fetchSinglePost = asyncHandler(async (req: Request, res: Response) => {
user_id: true,
User: {
select: {
user_id: true,
username: true,
pic: true,
},
Expand Down Expand Up @@ -260,17 +262,31 @@ const deletePost = asyncHandler(async (req: Request, res: Response) => {
},
where: { post_id: postId },
});

// @ts-ignore
const user_id = req.user.user_id;

if (!post) {
return res.status(404).json({ message: "Post not found" });
}

if (post.User.user_id !== user_id) {
return res.status(401).json({ message: "Unauthorized" });
}
await prisma.$transaction(async (prisma) => {
await prisma.comment.deleteMany({
where: { post_id: postId },
});
await prisma.like.deleteMany({
where: { post_id: postId },
});

return res.status(200).json({ message: "Post deleted" });
await prisma.post.delete({
where: { post_id: postId },
});
});

return res.status(200).json({ message: "Post and comments deleted" });
});

// @ts-ignore
Expand Down Expand Up @@ -374,6 +390,10 @@ const deleteComment = asyncHandler(async (req: Request, res: Response) => {
return res.status(401).json({ message: "Unauthorized" });
}

await prisma.comment.delete({
where: { comment_id: commentId },
});

return res.status(200).json({ message: "Comment deleted" });
});

Expand Down
36 changes: 36 additions & 0 deletions frontend/src/components/DeleteConfirmation.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from "react";
import {
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Text,
} from "@chakra-ui/react";

const DeleteConfirmation = ({ isOpen, onClose, onConfirm, message }) => {
return (
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent bg="gray.800" color="whiteAlpha.900">
{" "}
<ModalHeader>Confirm Deletion</ModalHeader>
<ModalBody>
<Text>{message}</Text>
</ModalBody>
<ModalFooter>
<Button colorScheme="blue" mr={3} onClick={onClose}>
Cancel
</Button>
<Button colorScheme="red" onClick={onConfirm}>
Delete
</Button>
</ModalFooter>
</ModalContent>
</Modal>
);
};

export default DeleteConfirmation;
104 changes: 98 additions & 6 deletions frontend/src/components/SinglePost.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useEffect, useState } from "react";
import { GrLike } from "react-icons/gr";
import { useNavigate } from "react-router-dom";
import { AiFillLike } from "react-icons/ai";
import { useParams, Navigate } from "react-router-dom";
import {
Expand All @@ -13,24 +14,31 @@ import {
Center,
VStack,
useToast,
Icon,
} from "@chakra-ui/react";
import { gsap } from "gsap";
import axios from "axios";
import CreateComment from "./CreateComment";
import { useUser } from "../hook/useUser";
import { InfinitySpin } from "react-loader-spinner";
import DeleteConfirmation from "./DeleteConfirmation";
import { FaTrash } from "react-icons/fa";

const SinglePost = () => {
const { id } = useParams();
const [post, setPost] = useState(null);
const [loading, setLoading] = useState(true);
const [postLiked, setPostLiked] = useState(false);
const { userDetails, loadingUser } = useUser();
const [isDeletePostOpen, setIsDeletePostOpen] = useState(false);
const [isDeleteCommentOpen, setIsDeleteCommentOpen] = useState(false);
const [commentToDelete, setCommentToDelete] = useState(null);

// Refs for the animations
const likeButtonRef = React.useRef(null);
const likeFloodRef = React.useRef(null);
const toast = useToast();
const navigate = useNavigate();

useEffect(() => {
const fetchPost = async () => {
Expand All @@ -43,6 +51,7 @@ const SinglePost = () => {
} catch (err) {
setLoading(false);
alert("Error fetching post");
console.error("Error fetching post:", err);
}
};

Expand Down Expand Up @@ -163,6 +172,47 @@ const SinglePost = () => {
</Center>
);

const handleDeleteComment = async (comment) => {
try {
await axios.post(
"/api/post/deletecomment",
{ commentId: comment.comment_id },
{ withCredentials: true }
);
setPost((prevPost) => ({
...prevPost,
Comments: prevPost.Comments.filter(
(c) => c.comment_id !== comment.comment_id
),
}));
setIsDeleteCommentOpen(false);
} catch (error) {
console.error("Error deleting comment:", error);
}
};

const handleDeletePost = async () => {
try {
setLoading(true);
await axios.post(
"/api/post/deletepost",
{ postId: post.post_id },
{ withCredentials: true }
);
setIsDeletePostOpen(false);
setLoading(false);
toast({
title: "Post deleted successfully",
status: "success",
duration: 5000,
isClosable: true,
});
navigate("/posts");
} catch (error) {
console.error("Error deleting post:", error);
}
};

return (
<Box
p={6}
Expand Down Expand Up @@ -210,9 +260,29 @@ const SinglePost = () => {
{post.likes} {post.likes === 1 ? "like" : "likes"}
</Text>
</Flex>
<Button size="sm" colorScheme="teal" variant="solid">
Comments
</Button>
<Flex>
{post.User.user_id === userDetails.user_id && (
<Button
size="sm"
colorScheme="red"
variant="ghost"
onClick={() => {
setIsDeletePostOpen(true);
}}
leftIcon={<Icon as={FaTrash} />}
color="white"
_hover={{ bg: "red.600" }}
>
Delete
</Button>
)}
</Flex>
<DeleteConfirmation
isOpen={isDeletePostOpen}
onClose={() => setIsDeletePostOpen(false)}
onConfirm={handleDeletePost}
message="Are you sure you want to delete this post?"
/>
</Flex>
<Box
ref={likeFloodRef}
Expand All @@ -236,8 +306,6 @@ const SinglePost = () => {
<Box w="full" mt={4}>
<CreateComment postId={post.post_id} />
</Box>

{/* Displaying Comments */}
{post.Comments.length > 0 ? (
post.Comments.map((comment) => (
<Box
Expand All @@ -256,9 +324,33 @@ const SinglePost = () => {
{comment.User.username}
</Text>
</Flex>
<Text fontSize="large" color="gray.300">
<Text fontSize="large" color="gray.300" mb={2} paddingTop={2.5}>
{comment.content}
</Text>
{comment.User.user_id === userDetails.user_id && (
<Flex justify="flex-end" mt={2}>
<Button
size="sm"
colorScheme="red"
variant="ghost"
onClick={() => {
setCommentToDelete(comment);
setIsDeleteCommentOpen(true);
}}
leftIcon={<Icon as={FaTrash} />}
color="white"
_hover={{ bg: "red.600" }}
>
Delete
</Button>
<DeleteConfirmation
isOpen={isDeleteCommentOpen}
onClose={() => setIsDeleteCommentOpen(false)}
onConfirm={() => handleDeleteComment(commentToDelete)}
message="Are you sure you want to delete this comment?"
/>
</Flex>
)}
</Box>
))
) : (
Expand Down

0 comments on commit c986d7f

Please sign in to comment.