Skip to content

Commit

Permalink
feat: forum - upvote | downvote | saved
Browse files Browse the repository at this point in the history
  • Loading branch information
vishalkondle-dev committed Jul 9, 2024
1 parent 58377d7 commit 9545be4
Show file tree
Hide file tree
Showing 7 changed files with 303 additions and 105 deletions.
17 changes: 12 additions & 5 deletions app/(private)/forum/[forum]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
'use client';

import { Button, Group } from '@mantine/core';
import { Button, Group, Stack } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { Forum, AskQuestion } from '@/components/Forum';
import { Forum, AskQuestion, ReplyToQuestion } from '@/components/Forum';
import useFetchData from '@/hooks/useFetchData';
import { ForumType } from '@/components/Forum/Forum.types';

const ForumPage = ({ params }: { params: { forum: string } }) => {
const { data, loading } = useFetchData(`/api/forums?_id=${params.forum}`);
const { data, refetch } = useFetchData(`/api/forums?_id=${params.forum}`);
const [opened, { open, close }] = useDisclosure(false);

if (loading) {
if (!data?.length) {
return <></>;
}

Expand All @@ -18,7 +19,13 @@ const ForumPage = ({ params }: { params: { forum: string } }) => {
<Group mb="md" justify="right">
<Button onClick={open}>Ask Question</Button>
</Group>
<Forum forum={data[0]} />
<Stack gap="xl">
<Forum forum={data?.[0]} refetch={refetch} />
{data?.[1]?.map((forum: ForumType) => (
<Forum key={String(forum._id)} forum={forum} refetch={refetch} />
))}
<ReplyToQuestion refetch={refetch} parent={data[0]?._id} />
</Stack>
<AskQuestion opened={opened} close={close} />
</>
);
Expand Down
24 changes: 24 additions & 0 deletions app/api/forums/reply/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { getServerSession } from 'next-auth';
import { NextRequest, NextResponse } from 'next/server';
import startDb from '@/lib/db';
import Forum from '@/models/Forum';
import { authOptions } from '../../auth/[...nextauth]/authOptions';
import { UserDataTypes } from '../../auth/[...nextauth]/next-auth.interfaces';

export const maxDuration = 60;
export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
try {
const session: UserDataTypes | null = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: 'You are not authorized' }, { status: 401 });
}
const body = await req.json();
await startDb();
const forum = await Forum.create({ ...body, user: session?.user._id });
return NextResponse.json(forum, { status: 200 });
} catch (error: any) {
return NextResponse.json({ error: error?.message }, { status: 500 });
}
}
21 changes: 16 additions & 5 deletions app/api/forums/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getServerSession } from 'next-auth';
import { NextRequest, NextResponse } from 'next/server';
import mongoose from 'mongoose';
import startDb from '@/lib/db';
import Forum from '@/models/Forum';
import { authOptions } from '../auth/[...nextauth]/authOptions';
Expand All @@ -19,16 +20,25 @@ export async function GET(req: NextRequest) {
const tags = req.nextUrl.searchParams.get('tag')?.toString() ?? '';

if (_id) {
const forum = await Forum.find({ _id }).populate('user');
return NextResponse.json(forum, { status: 200 });
const forum = await Forum.findById(_id).populate({ path: 'user', select: 'name' });
const answers = await Forum.find({ parent: _id }).populate({ path: 'user', select: 'name' });
if (!forum?.views.includes(new mongoose.Types.ObjectId(session?.user._id))) {
await forum?.updateOne({ $push: { views: session?.user._id } }, { new: true });
}
return NextResponse.json([forum, answers], { status: 200 });
}

if (tags) {
const forums = await Forum.find({ tags }).populate('user').sort('-updatedAt');
const forums = await Forum.find({ tags })
.populate({ path: 'user', select: 'name' })
.sort('-updatedAt');
return NextResponse.json(forums, { status: 200 });
}

const forums = await Forum.find({}).populate('user').sort('-updatedAt');
const forums = await Forum.find({ question: { $exists: true }, description: { $exists: true } })
.populate({ path: 'user', select: 'name' })
.sort('-updatedAt');

return NextResponse.json(forums, { status: 200 });
} catch (error: any) {
return NextResponse.json({ error: error?.message }, { status: 500 });
Expand Down Expand Up @@ -58,7 +68,7 @@ export async function PUT(req: NextRequest) {
}
const body = await req.json();
await startDb();
const forum = await Forum.findByIdAndUpdate(body._id, body);
const forum = await Forum.findByIdAndUpdate(body._id, body, { new: true });
return NextResponse.json(forum, { status: 200 });
} catch (error: any) {
return NextResponse.json({ error: error?.message }, { status: 500 });
Expand All @@ -73,6 +83,7 @@ export async function DELETE(req: NextRequest) {
}
await startDb();
await Forum.findByIdAndDelete(req.nextUrl.searchParams.get('_id'));
await Forum.deleteMany({ parent: req.nextUrl.searchParams.get('_id') });
return NextResponse.json(null, { status: 200 });
} catch (error: any) {
return NextResponse.json({ error: error?.message }, { status: 500 });
Expand Down
Loading

0 comments on commit 9545be4

Please sign in to comment.