Skip to content

Commit

Permalink
DN-4: Success in creating and getting comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereckmezquita committed Jul 15, 2024
1 parent f5bd0cd commit 9a07a1e
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 23 deletions.
67 changes: 48 additions & 19 deletions client/src/app/test/api/demos/CommentsDemo.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
'use client';
import React, { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { usePathname } from 'next/navigation';
import { IndicateLoading } from '@components/components/atomic/IndiacteLoading';
import { api } from '@components/utils/api/api';
import { useAuth } from '@components/context/AuthContext';

interface Comment {
_id: string;
content: string;
author: string;
author: {
id: string;
username: string;
};
createdAt: string;
likes: string[];
replies: string[];
Expand All @@ -27,19 +32,27 @@ export function CommentsDemo() {
const [page, setPage] = useState(1);
const [newComment, setNewComment] = useState('');
const pathname = usePathname();
const { user, loading: authLoading } = useAuth();

useEffect(() => {
async function fetchComments() {
setLoading(true);
const toastId = toast.loading('Fetching comments...');
try {
setLoading(true);
const encodedPathname = encodeURIComponent(pathname);
const response = await api.get<CommentsResponse>(
`/comments/${pathname}?page=${page}&limit=10`
`/comments/${encodedPathname}?page=${page}&limit=10`
);
console.log(response.data.comments);
setComments(response.data.comments);
setTotalComments(response.data.total);
} catch (error) {
toast.success('Comments loaded successfully', { id: toastId });
} catch (error: any) {
console.error('Error fetching comments:', error);
// Handle error (e.g., show error message to user)
toast.error(
'Failed to fetch comments. Please try again later.',
{ id: toastId }
);
} finally {
setLoading(false);
}
Expand All @@ -50,21 +63,33 @@ export function CommentsDemo() {

const handleSubmitComment = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) {
toast.error('Please log in to submit a comment.');
return;
}
const toastId = toast.loading('Submitting comment...');
try {
const encodedPathname = encodeURIComponent(pathname);
const response = await api.post('/comments', {
content: newComment,
post: pathname,
// You'll need to get the author ID from your auth system
author: 'current-user-id'
post: encodedPathname,
author: user.id
});
setComments([response.data, ...comments]);
setNewComment('');
toast.success('Comment submitted successfully', { id: toastId });
} catch (error) {
console.error('Error submitting comment:', error);
// Handle error (e.g., show error message to user)
toast.error('Failed to submit comment. Please try again.', {
id: toastId
});
}
};

if (authLoading) {
return <IndicateLoading />;
}

return (
<div>
<h2>Comments for: {pathname}</h2>
Expand All @@ -73,21 +98,25 @@ export function CommentsDemo() {
) : (
<>
<p>Total comments: {totalComments}</p>
<form onSubmit={handleSubmitComment}>
<textarea
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
placeholder="Write a comment..."
required
/>
<button type="submit">Submit Comment</button>
</form>
{user ? (
<form onSubmit={handleSubmitComment}>
<textarea
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
placeholder="Write a comment..."
required
/>
<button type="submit">Submit Comment</button>
</form>
) : (
<p>Please log in to leave a comment.</p>
)}
<ul>
{comments.map((comment) => (
<li key={comment._id}>
<p>{comment.content}</p>
<small>
By: {comment.author} on{' '}
By: {comment.author.username} on{' '}
{new Date(
comment.createdAt
).toLocaleString()}
Expand Down
13 changes: 9 additions & 4 deletions server/src/routes/comments/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ const router = express.Router();
/**
* Allows fetching top-level comments and replies
*/
router.get('/comments/:postSlug', async (req: Request, res: Response) => {
const { postSlug } = req.params;
router.get('/comments/:post', async (req: Request, res: Response) => {
const { post } = req.params;
const { depth = 1, limit = 10, page = 1 } = req.query;

const decodedPost = decodeURIComponent(post);

try {
const { comments, total } = await Comment.findByPostSlug(postSlug, {
const { comments, total } = await Comment.findByPostSlug(decodedPost, {
depth: Number(depth),
limit: Number(limit),
page: Number(page)
Expand All @@ -30,8 +32,11 @@ router.get('/comments/:postSlug', async (req: Request, res: Response) => {

// Create a new comment
router.post('/comments', async (req: Request, res: Response) => {
// TODO: get the author from the request session
const { content, author, post, parentComment } = req.body;

const decodedPost = decodeURIComponent(post);

try {
let depth = 0;
if (parentComment) {
Expand All @@ -42,7 +47,7 @@ router.post('/comments', async (req: Request, res: Response) => {
const newComment = new Comment({
content,
author,
post,
post: decodedPost,
parentComment,
depth
});
Expand Down

0 comments on commit 9a07a1e

Please sign in to comment.