Skip to content

Commit

Permalink
bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
imdeveshshukla committed Aug 25, 2024
1 parent 3cc7487 commit fcb6148
Show file tree
Hide file tree
Showing 20 changed files with 306 additions and 51 deletions.
36 changes: 36 additions & 0 deletions backend/src/controller/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,42 @@ export const getAllComment = async (req,res)=>{
});
}
}
export const deleteComment = async(req,res)=>{
const userId = req.userId;
const id = req.body.id;

try{
const cmnt = await prisma.comment.findFirst({
where:{
id
}
});
console.log(cmnt.userId);
console.log(userId);
if(cmnt.userId !== userId)
{
return res.status(403).json({
msg:"You Are Not Authorised"
})
}
await prisma.comment.delete({
where:{
id
}
});
return res.status(201).json({
msg:"Success"
});
}
catch(err)
{
return res.status(500).json({
msg:"Server Issue",
err
})
}

}

export const getUserComment = async (req,res)=>{
const { uId } = req.userId;
Expand Down
40 changes: 38 additions & 2 deletions backend/src/controller/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import prisma from "../../db/db.config.js";
import zod from "zod";
import uploadOnCloudinary from "../utils/cloudinary.js";
import { stringify } from "bigint-json";
import fs from "fs";
const post = zod.object({
topic: zod.string().optional(),
title: zod.string(),
Expand Down Expand Up @@ -186,6 +185,43 @@ export const getHotPost = async (req, res) => {
}
};

export const deletePost = async(req,res) =>{
const userId = req.userId;
const id = req.body.id;
console.log(id);
try{

const post = await prisma.post.findFirst({
where:{
id
}
})
if(post.userId != userId)
{
return res.status(403).json({
msg:'Unautorised'
})
}
console.log(post);
const data = await prisma.post.delete({
where:{
id
}
});
return res.status(201).json({
msg:"Success",
data
})
}
catch(err){
return res.status(500).json({
msg:"Server Issue",
err
});
}
}


export const getPopularPosts = async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
Expand Down Expand Up @@ -227,7 +263,7 @@ export const getPopularPosts = async (req, res) => {
LEFT JOIN "User" u ON u."userID" = p."userId"
ORDER BY "popularityScore" DESC, p."createdAt" DESC
LIMIT ${limit} OFFSET ${offset};
`;
`;


let posts = JSON.parse(stringify(result));
Expand Down
2 changes: 2 additions & 0 deletions backend/src/controller/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export const getUser = async (req, res) => {
createdAt: true,
leetcode: true,
showLC: true,
showCf:true,
codeforces:true,
_count: {
select: {
posts: true,
Expand Down
6 changes: 4 additions & 2 deletions backend/src/routes/posts.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import express from "express"
import { verifyToken } from "../middlewares/verifytoken.js";
import { createPost, getPost,getAPost,getHotPost, getPopularPosts } from "../controller/posts.js";
import { createPost, getPost,getAPost,getHotPost, getPopularPosts, deletePost } from "../controller/posts.js";
import { upload } from "../middlewares/multer.js";
import { createComment, getAllComment, getUserComment } from "../controller/comment.js";
import { createComment, deleteComment, getAllComment, getUserComment } from "../controller/comment.js";
import { upvoteNumber, vote } from "../controller/upvotes.js";

const postRoutes = express.Router();
Expand All @@ -21,6 +21,7 @@ postRoutes.get("/getPost",getPost);
postRoutes.get("/getaPost",getAPost);
postRoutes.post("/postWithImg",verifyToken,upload.single('postImg'),createPost);
postRoutes.post("/post",verifyToken,createPost);
postRoutes.delete("/delete",verifyToken,deletePost);

//hotTopicsPost
postRoutes.get("/q/hottopic", getHotPost);
Expand All @@ -31,6 +32,7 @@ postRoutes.get('/popular',getPopularPosts);
postRoutes.post('/createcomment',verifyToken,createComment);
postRoutes.post('/getallcomment',getAllComment);
postRoutes.get('/comment',getUserComment);
postRoutes.delete('/deleteComment',verifyToken,deleteComment);

//create getComment according to postID

Expand Down
17 changes: 17 additions & 0 deletions frontend/src/components/Codeforces.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export default function Codeforces({ rating }){
const getItem = {
"newbie": <p className="text-gray-500">newbie</p>,
"pupil":<p className="text-green-500">pupil</p>,
"specialist":<p className="text-blue-300">specialist</p>,
"expert":<p className="text-blue-600">expert</p>,
"candidate master":<p className="text-purple-500">Candidate master</p>,
"master":<p className="text-orange-500">master</p>,
"international master":<p className="text-orange-600">International master</p>,
"grandmaster":<p className="text-red-600">Grandmaster</p>,
"international grandmaster":<p className="text-red-700">International Grandmaster</p>,
"legendary grandmaster":<p className="text-red-700"><span className="text-black">legendary</span> Grandmaster</p>

}

return getItem[rating];
}
66 changes: 62 additions & 4 deletions frontend/src/components/Comments.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import axios from 'axios';

import React, { useEffect, useState } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import toast from 'react-hot-toast';
import SmallLoader from './SmallLoader';
import { setComment } from '../redux/Postdetail';
import { clearPostDetail, delComment, setComment } from '../redux/Postdetail';
import { setUserPostComment } from '../redux/userposts';
import { setPostComment } from '../redux/Post';
import { clearPostsInfo, setPostComment } from '../redux/Post';
import { BiDownvote, BiUpvote } from 'react-icons/bi';
import { GoComment } from 'react-icons/go';
import { RiShareForwardLine } from 'react-icons/ri';
Expand All @@ -29,6 +29,9 @@ import { getTime } from './Posts';
import ReadMore from './ReadMore';
import baseAddress from '../utils/localhost';
import { useNavigate } from 'react-router-dom';
import { BsThreeDotsVertical } from 'react-icons/bs';
import SmoothLoader from '../assets/SmoothLoader';
import { MdDelete } from 'react-icons/md';



Expand Down Expand Up @@ -137,9 +140,44 @@ export function CommentBody2({ id, dp, body, user, createdAt, getTime, getChildr
const [showChild, setShowChild] = useState(false);
const childs = getChildren(id) == undefined ? [] : getChildren(id);
const userInfo = useSelector(state => state.user.userInfo);
const isLogin = useSelector(state => state.login.value);
const Navigate= useNavigate();
const [isOpen,setOpen] = useState(false);
const [delLoading,setLoading] = useState(false);
const dropdownRef = useRef(null);
const dispatch = useDispatch();
const handleToggle = ()=>{
setOpen((v)=>!v)
}
const handleClickOutside = (event) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
setOpen(false);
}


};
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
async function deleteComment(id){
setLoading(true);
// console.log(userInfo?.userID);
try {
const res = await axios.delete(`${baseAddress}posts/deleteComment`,{
data:{
id
}
})
dispatch(delComment(id));
toast.success(res?.data.msg);
} catch (error) {
toast.error(error.response?.data.msg);
console.log(error);
}
setLoading(false);
}
function handleComment(id) {
setOpenBox((openBox) => !openBox);

Expand Down Expand Up @@ -258,6 +296,26 @@ export function CommentBody2({ id, dp, body, user, createdAt, getTime, getChildr
{/* <a className="text-gray-500 text-xl" href="#"><i className="fa-solid fa-trash"></i></a> */}
</div><span></span>
<p className="text-gray-500 text-[9px] xxs:text-xs line-clamp-1 overflow-clip">{getTime(createdAt)} ago</p>
{isLogin&&
<div className="relative flex items-center gap-8 ml-auto" ref={dropdownRef} >

<button onClick={handleToggle} className="flex items-center hover:focus:outline-none">
<BsThreeDotsVertical/>
</button>
{isOpen && (
<div className="absolute right-0 top-4 bg-white rounded-md shadow-lg z-10">
<ul className=" bg-[#6d712eb8] rounded-md ">
<li className=" text-white hover:text-black">
<button onClick={() => deleteComment(id)} className="px-4 py-1 flex items-center gap-1 ">
{delLoading?<SmoothLoader/>:<><span>Delete</span> <MdDelete /></>}</button>
</li>
</ul>

</div>
)}
</div>

}
</div>
</div>
<div className=' mx-10 text-sm xs:text-base whitespace-pre-wrap break-words'><ReadMore maxLines={3} children={body} /></div>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/Notification.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const Notification = ({setIsNfnOpen}) => {
}

const getUserNotification = async()=>{

try {
const res = await axios.get(baseAddress+"u/notification", { withCredentials: true });
dispatch(setNotification(res.data.data))
Expand Down
37 changes: 22 additions & 15 deletions frontend/src/components/Postdetail.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import Postskelton from './Postskelton';
import { setUserPostComment } from '../redux/userposts';
import { CommentBody, CommentBody2, CommentBox } from './Comments';
import baseAddress from '../utils/localhost';
import ForbiddenPage from '../pages/ForbiddenPage';



Expand All @@ -30,17 +31,21 @@ const Postdetail = ({ myRooms }) => {
const location = useLocation();
const {id}= useParams();
const {roomid} = useParams();

const [room,setRoom] = useState({});
const [displayPost,setDisp] = useState(true);
const [loading,setLoading] = useState(false);
const getApost=async()=>{
if(myRooms){
if(roomid){
let found = false;
// console.log(myRooms);
// console.log(roomid);
myRooms.map((room)=>{
if(room.room.id === roomid)found = true;
if(room.room.id === roomid)
{
found = true;
setRoom(room.room);
}
});
if(!found){
toast.error("Unauthorised");
setDisp(false);
return;
}
}
Expand All @@ -60,9 +65,11 @@ const Postdetail = ({ myRooms }) => {
}

useEffect(() => {
setLoading(true)
dispatch(clearPostDetail())
getApost()
},[])
getApost()
setLoading(false);
},[isLogin])



Expand Down Expand Up @@ -96,11 +103,11 @@ const Postdetail = ({ myRooms }) => {
function getChildren(id){
return groupComments[id]
}
// console.log("Groupd Comments = "+JSON.stringify(groupComments));
return (<>
if(!displayPost && !loading)return <ForbiddenPage/>
else return (<>
<div className=' min-h-screen overflow-auto xs:pl-4 sm:pl-16 1_5md:pl-2 2_md:pl-16'>
{post?<Posts key={post?.id} id={post?.id} title={post?.title} body={post?.body} media={post?.img} countComment={post?.comments?.length} createdAt={post?.createdAt} user={post?.user} upvotes={post?.upvotes} postDetails={true}/>:<Postskelton/>}

{post?<Posts key={post?.id} id={post?.id} title={post?.title} inRoom={roomid?true:false} room={room} joined={roomid?true:false} body={post?.body} media={post?.img} countComment={post?.comments?.length} createdAt={post?.createdAt} user={post?.user} upvotes={post?.upvotes} postDetails={true}/>:<Postskelton/>}
<div className=' m-4'>
{isLogin? <CommentBox/>

Expand All @@ -111,9 +118,9 @@ const Postdetail = ({ myRooms }) => {

<div className=' m-2 xs:m-4'>
<div className=' text-xl font-bold mb-4 underline'>Comments:</div>
{/* {console.log(post?.comments)}; */}
<CommentBody comments={groupComments[null]} postId={post?.id} getChildren={getChildren} userId={userInfo?.userID} dp={dp} getTime={getTime}/>
{/* <CommentBody comments={post?.comments} dp={dp} getTime={getTime}/> */}

<CommentBody comments={groupComments[null]} postId={post?.id} getChildren={getChildren} userId={post?.userId} dp={dp} getTime={getTime}/>

</div>

</div>
Expand Down
Loading

0 comments on commit fcb6148

Please sign in to comment.