From dbc1a5ae06067ec84f5eb3c77842583cad1489c1 Mon Sep 17 00:00:00 2001 From: Devesh Shukla Date: Sun, 8 Sep 2024 02:17:26 +0530 Subject: [PATCH] hottopicposts --- .../20240907193820_development/migration.sql | 2 + backend/prisma/schema.prisma | 1 + backend/src/controller/poll.js | 49 +++++- backend/src/controller/posts.js | 1 + backend/src/routes/poll.js | 4 +- frontend/src/App.jsx | 14 +- frontend/src/components/Polls.jsx | 2 +- frontend/src/pages/CreatePost.jsx | 29 ++++ frontend/src/pages/HotTopicPosts.jsx | 162 ++++++++++++++++-- frontend/src/pages/Room.jsx | 26 ++- 10 files changed, 251 insertions(+), 39 deletions(-) create mode 100644 backend/prisma/migrations/20240907193820_development/migration.sql diff --git a/backend/prisma/migrations/20240907193820_development/migration.sql b/backend/prisma/migrations/20240907193820_development/migration.sql new file mode 100644 index 0000000..7fe8b0e --- /dev/null +++ b/backend/prisma/migrations/20240907193820_development/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Poll" ADD COLUMN "topic" TEXT; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 9007101..d1c4f70 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -47,6 +47,7 @@ model User{ model Poll { id String @id @default(uuid()) title String + topic String? description String? options PollOption[] createdAt DateTime @default(now()) diff --git a/backend/src/controller/poll.js b/backend/src/controller/poll.js index 61b07d0..918719a 100644 --- a/backend/src/controller/poll.js +++ b/backend/src/controller/poll.js @@ -1,20 +1,22 @@ import prisma from "../../db/db.config.js"; export const createPoll = async (req, res) => { - const { title, options,subCommunity } = req.body; + const { title, options,subCommunity,topic } = req.body; try { const poll = await prisma.poll.create({ data: { title, + topic, options: { create: options.map((option) => ({ text: option, })), }, userId: req.userId, - subCommunity: subCommunity + subCommunity: subCommunity, }, }); + // console.log(poll); res.status(200).send(poll); } catch (error) { console.log(error); @@ -115,6 +117,9 @@ export const getPoll = async (req, res) => { }; + + + export const getAllPolls= async(req,res)=>{ const limit= parseInt(req.query.limit) ||15; @@ -150,6 +155,43 @@ export const getAllPolls= async(req,res)=>{ } } +export const getHotPolls = async(req,res)=>{ + const topic = req.query.topic; + const page = parseInt(req.query.page) || 1; + const limit = parseInt(req.query.limit) || 10; + const offset = (page - 1) * limit; + + console.log(topic) + try { + const polls = await prisma.poll.findMany({ + where:{ + topic + }, + include: { + options: { + include: { + votes: true, + }, + }, + createdBy:true + }, + orderBy: { + createdAt: "desc", + }, + skip: offset, + take: limit, + }) + console.log(polls); + res.status(200).send(polls); + } catch (error) { + res.status(500).json({ + msg:"Server Issue", + error:error.message + }) + } +} + + export const deletePoll = async(req,res)=>{ const id= req.query.id; @@ -208,4 +250,5 @@ export const isPollFromRoom = async(req,res)=>{ msg:"Server Issue" }) } -} \ No newline at end of file +} + diff --git a/backend/src/controller/posts.js b/backend/src/controller/posts.js index 2c14b73..bc9cdcd 100644 --- a/backend/src/controller/posts.js +++ b/backend/src/controller/posts.js @@ -228,6 +228,7 @@ export const deletePost = async(req,res) =>{ } + export const getPopularPosts = async (req, res) => { const page = parseInt(req.query.page) || 1; const limit = parseInt(req.query.limit) || 10; diff --git a/backend/src/routes/poll.js b/backend/src/routes/poll.js index c99ea92..6621b23 100644 --- a/backend/src/routes/poll.js +++ b/backend/src/routes/poll.js @@ -1,6 +1,6 @@ import express from "express" import { verifyToken } from "../middlewares/verifytoken.js"; -import { createPoll, deletePoll, getAllPolls, getPoll, isPollFromRoom, votePoll } from "../controller/poll.js"; +import { createPoll, deletePoll, getAllPolls, getHotPolls, getPoll, isPollFromRoom, votePoll } from "../controller/poll.js"; const pollRoutes = express.Router(); @@ -8,6 +8,8 @@ const pollRoutes = express.Router(); pollRoutes.get('/getpoll/', getPoll ); pollRoutes.get('/getpollRoom',verifyToken,isPollFromRoom); pollRoutes.get('/getallpolls/', getAllPolls); + +pollRoutes.get('/q/hottopicspoll',getHotPolls) pollRoutes.post('/createpoll', verifyToken, createPoll ); pollRoutes.post('/votepoll', verifyToken, votePoll ); pollRoutes.delete('/deletepoll',verifyToken,deletePoll); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index ec0fae1..1e99395 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -23,7 +23,7 @@ import baseAddress from "./utils/localhost"; import Postdetail from './components/Postdetail' import Postskelton, { CommentSkelton, PollSkelton, ProfileSkelton } from './components/Postskelton' import { setSkeltonLoader } from './redux/skelton' -import HotTopicPosts from './pages/HotTopicPosts' +import HotTopicPosts, { HotTopicPostsorPolls } from './pages/HotTopicPosts' import sportsdp from './assets/sportsdp.jpg' import sportsbg from './assets/sportsbg.jpg' import ietdp from './assets/ietdp.png' @@ -241,12 +241,12 @@ function App() { } /> } /> - } /> - } /> - } /> - } /> - } /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/frontend/src/components/Polls.jsx b/frontend/src/components/Polls.jsx index ab674c2..cab6a4f 100644 --- a/frontend/src/components/Polls.jsx +++ b/frontend/src/components/Polls.jsx @@ -209,7 +209,7 @@ const deletePoll=async(id)=>{ Navigate(`/u/${poll?.createdBy?.username}`)} src={poll?.createdBy?.dp || dp} alt="Profile" className="w-8 h-8 rounded-full cursor-pointer bg-white" />
Navigate(`/u/${poll?.createdBy?.username}`)} className='font-semibold cursor-pointer hover:text-green-900'>u/{poll?.createdBy?.username}•{(inRoom && <> Navigate(`/room/${user.userID}/${room?.title}`)} className=' cursor-pointer hover:text-rose-900 text-sm font-semibold'>q/{room?.title} ) - || (topic && <> Navigate(`/q/${"topic"}`)} className=' cursor-pointer hover:text-rose-900 text-sm font-semibold'>q/{topic} )}{`${getTime(poll?.createdAt)} ago`} + || (topic && <> Navigate(`/q/${topic}`)} className=' cursor-pointer hover:text-rose-900 text-sm font-semibold'>q/{topic} )}{`${getTime(poll?.createdAt)} ago`}
{ diff --git a/frontend/src/pages/CreatePost.jsx b/frontend/src/pages/CreatePost.jsx index 509fd31..9e9dd5f 100644 --- a/frontend/src/pages/CreatePost.jsx +++ b/frontend/src/pages/CreatePost.jsx @@ -309,6 +309,11 @@ export const CreatePoll = () => { const dispatch = useDispatch() const Navigate = useNavigate() const { roomTitle,roomCreatorId } = useOutletContext() + const [selectedOption, setSelectedOption] = useState(null); + + const handleSelectChange = (event) => { + setSelectedOption(event.target.value); + }; const handleTitleChange=(e)=>{ @@ -345,6 +350,7 @@ export const CreatePoll = () => { const res = await axios.post(`${baseAddress}poll/createpoll`, { title: poll.title, options: poll.options, + topic: selectedOption, subCommunity:roomTitle }) @@ -373,6 +379,29 @@ export const CreatePoll = () => { return (

Create Poll....

+ {!roomTitle ?
+
+ + + + + q/ + + + +
+
+ : <> + }
diff --git a/frontend/src/pages/HotTopicPosts.jsx b/frontend/src/pages/HotTopicPosts.jsx index 62c8362..d0cb7bb 100644 --- a/frontend/src/pages/HotTopicPosts.jsx +++ b/frontend/src/pages/HotTopicPosts.jsx @@ -4,11 +4,69 @@ import baseAddress from "../utils/localhost"; import { useDispatch, useSelector } from 'react-redux'; import InfiniteScroll from 'react-infinite-scroll-component'; import axios from 'axios'; -import Postskelton from '../components/Postskelton'; +import Postskelton, { PollSkelton } from '../components/Postskelton'; import { clearHotPostsInfo, setHotPost } from '../redux/Hotposts'; import Posts from '../components/Posts'; import { GrRefresh } from 'react-icons/gr'; import SmallLoader from '../components/SmallLoader'; +import { clearPollInfo, setPoll } from '../redux/userpolls'; +import Polls from '../components/Polls'; + + +export const HotTopicPostsorPolls = ({ title, topic, dp, bg }) =>{ + const [disVal, setdisVal] = useState("post") + useEffect(()=>{ + setdisVal("post") + },[topic]) + return( + <> + +
+
+ +
+ setdisVal("post")} + checked={disVal === "post"} + type="radio" + value="post" + name="post_poll" + id="post" + /> + +
+
+ setdisVal("poll")} + checked={disVal === "poll"} + type="radio" + value="poll" + name="post_poll" + id="poll" + /> + +
+
+ + + {disVal==="post" && } + {disVal==="poll" && } + + +
+ + ) +} const HotTopicPosts = ({ title, topic, dp, bg }) => { const [isLoading, setisLoading] = useState(false); @@ -97,7 +155,7 @@ const HotTopicPosts = ({ title, topic, dp, bg }) => { return ( <> - +
{

} > -
- getPost(true, 1)} // Reset to fetch from page 1 - className="bg-[#eff1d3] rounded-full p-1" - > - {isLoading ? : ( - - )} - -
-
{ intLoading ? : hotposts.map((post) => ( { ); }; +export const HotTopicPolls = ({ title, topic })=>{ + const hotposts = useSelector(state => state.userpoll.polls); + const [page,setPage] = useState(0); + const [isLoading,setisLoading] = useState(false) + const [hasMore,setHasMore] = useState(true); + const dispatch = useDispatch(); + + async function getPolls(customPage){ + if (customPage == 1) { + dispatch(clearPollInfo()) + setHasMore(true); + setPage(1); + } + try { + + // console.log("InsidegetPolls ",isLoading) + const res = await axios.get(`${baseAddress}poll/q/hottopicspoll`, { + params: { + offset: customPage, + limit: 10, + topic:topic + } + }); + + if (res.status === 200) { + const fetchedPolls = res.data; + dispatch(setPoll(fetchedPolls)); + if (fetchedPolls?.length < 10) { + setHasMore(false); + } + + setisLoading(false); + console.log("InsidegetPolls ",isLoading) + } + } catch (error) { + console.log(error); + setHasMore(false); // Stop fetching if there's an error + setisLoading(false); + } + } + + useEffect(() => { + setisLoading(true) // Set loading to true during transition + setPage(1); + dispatch(clearPollInfo()); + getPolls(1); + }, [topic, title]); + + useEffect(() => { + if (page > 1) { + getPolls(page); + } + }, [page]); + + const fetchMoreData = () => { + if (!hasMore) return; + setPage((prevPage) => prevPage + 1); + }; + + return( +
+ + +
+ } + endMessage={ +

+ {`${hotposts.length === 0 + ? "It looks like there aren't any Polls yet." + : "You've reached the end of the page!"}`} +

+ } + > +
+ { hotposts.map((post) => ( + + ))} +
+ +
+ ) + +} + export default HotTopicPosts; diff --git a/frontend/src/pages/Room.jsx b/frontend/src/pages/Room.jsx index 22d691a..7d709fe 100644 --- a/frontend/src/pages/Room.jsx +++ b/frontend/src/pages/Room.jsx @@ -254,11 +254,11 @@ const Room = function () { } }, [data, title]) - useEffect(()=>{ - // console.log("Mai dis Value wala use Effect " ,disVal); - if(disVal==='poll') console.log("Changed To Poll LOL"); - else console.log("Changed To Post LOL");//getPost(true); - },[disVal]) + // useEffect(()=>{ + // // console.log("Mai dis Value wala use Effect " ,disVal); + // if(disVal==='poll') console.log("Changed To Poll LOL"); + // else console.log("Changed To Post LOL");//getPost(true); + // },[disVal]) useEffect(() => { // console.log("Mai joined or privateROom val useEffect",joined, privateRoom); @@ -518,7 +518,7 @@ export const RoomPost = ({title,privateRoom,joined,data})=>{ const [cancelTokenSource, setCancelTokenSource] = useState(null); const getPost = async (initial) => { if (cancelTokenSource) { - // cancelTokenSource.cancel('Previous request canceled due to new topic.'); + cancelTokenSource.cancel('Previous request canceled due to new topic.'); } const source = axios.CancelToken.source(); @@ -553,7 +553,7 @@ export const RoomPost = ({title,privateRoom,joined,data})=>{ dispatch(setHotPost(fetchedPosts)); if (fetchedPosts.length < 10) { - console.log("setHasMOre ",fetchedPosts.length) + // console.log("setHasMOre ",fetchedPosts.length) setHasMore(false); } setisLoading(false); @@ -581,7 +581,6 @@ export const RoomPost = ({title,privateRoom,joined,data})=>{ },[title,data,joined,privateRoom]) useEffect(() => { - // console.log(page," ",joined); if (joined || !privateRoom) { if(page>0)getPost(); @@ -589,7 +588,7 @@ export const RoomPost = ({title,privateRoom,joined,data})=>{ }, [page]) const fetchMoreData = () => { - if (isLoading || !hasMore) return; + if (!hasMore) return; setPage((prevPage) => prevPage + 10); }; @@ -652,22 +651,21 @@ export const RoomPolls = ({title,privateRoom,joined,data})=>{ },[title]) useEffect(() => { - console.log(page," ",joined); if (joined || !privateRoom) { if(page>0)getRoomsPolls(joined,privateRoom,dispatch,setPoll,clearPollInfo,setisLoading,isLoading,setHasMore,page,title); } }, [page]) const fetchMoreData = () => { - console.log("InPolls ",page,isLoading,hasMore); - if (isLoading || !hasMore) return; + // console.log("InPolls ",page,isLoading,hasMore); + if (!hasMore) return; setPage((prevPage) => prevPage + 10); }; - return
+ return
{privateRoom && !joined ? : { fetchMoreData }} + next={fetchMoreData} hasMore={hasMore} loader={} endMessage={hotposts.length > 0 ?

{"You've reached the end of the page!"}

:

No Polls available to display!

}