mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Update: Refactor comments section to prop drill edit and delete handlers
This commit is contained in:
@@ -3,6 +3,7 @@ import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResul
|
||||
import { FC, useState } from 'react';
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
import { z } from 'zod';
|
||||
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
|
||||
import CommentContentBody from './CommentContentBody';
|
||||
import EditCommentBody from './EditCommentBody';
|
||||
|
||||
@@ -10,20 +11,36 @@ interface CommentCardProps {
|
||||
comment: z.infer<typeof CommentQueryResult>;
|
||||
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
|
||||
ref?: ReturnType<typeof useInView>['ref'];
|
||||
handleDeleteRequest: (id: string) => Promise<void>;
|
||||
handleEditRequest: (
|
||||
id: string,
|
||||
data: z.infer<typeof CreateCommentValidationSchema>,
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
|
||||
const CommentCardBody: FC<CommentCardProps> = ({
|
||||
comment,
|
||||
mutate,
|
||||
ref,
|
||||
handleDeleteRequest,
|
||||
handleEditRequest,
|
||||
}) => {
|
||||
const [inEditMode, setInEditMode] = useState(false);
|
||||
|
||||
return !inEditMode ? (
|
||||
<CommentContentBody comment={comment} ref={ref} setInEditMode={setInEditMode} />
|
||||
) : (
|
||||
<EditCommentBody
|
||||
comment={comment}
|
||||
mutate={mutate}
|
||||
setInEditMode={setInEditMode}
|
||||
ref={ref}
|
||||
/>
|
||||
return (
|
||||
<div ref={ref}>
|
||||
{!inEditMode ? (
|
||||
<CommentContentBody comment={comment} setInEditMode={setInEditMode} />
|
||||
) : (
|
||||
<EditCommentBody
|
||||
comment={comment}
|
||||
mutate={mutate}
|
||||
setInEditMode={setInEditMode}
|
||||
handleDeleteRequest={handleDeleteRequest}
|
||||
handleEditRequest={handleEditRequest}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -36,7 +36,14 @@ const CommentCardDropdown: FC<CommentCardDropdownProps> = ({
|
||||
Edit
|
||||
</button>
|
||||
) : (
|
||||
<button>Report</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
alert('This feature is not yet implemented.');
|
||||
}}
|
||||
>
|
||||
Report
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -4,26 +4,21 @@ import { format } from 'date-fns';
|
||||
import { Dispatch, FC, SetStateAction, useContext } from 'react';
|
||||
import { Link, Rating } from 'react-daisyui';
|
||||
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
|
||||
import { z } from 'zod';
|
||||
import CommentCardDropdown from './CommentCardDropdown';
|
||||
|
||||
interface CommentContentBodyProps {
|
||||
comment: z.infer<typeof CommentQueryResult>;
|
||||
ref: ReturnType<typeof useInView>['ref'] | undefined;
|
||||
setInEditMode: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
const CommentContentBody: FC<CommentContentBodyProps> = ({
|
||||
comment,
|
||||
ref,
|
||||
setInEditMode,
|
||||
}) => {
|
||||
const CommentContentBody: FC<CommentContentBodyProps> = ({ comment, setInEditMode }) => {
|
||||
const { user } = useContext(UserContext);
|
||||
const timeDistance = useTimeDistance(new Date(comment.createdAt));
|
||||
|
||||
return (
|
||||
<div className="card-body animate-in fade-in-10" ref={ref}>
|
||||
<div className="card-body animate-in fade-in-10">
|
||||
<div className="flex flex-row justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold sm:text-2xl">
|
||||
|
||||
@@ -1,38 +1,44 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { FC, useState, useEffect, Dispatch, SetStateAction } from 'react';
|
||||
import { FC, useState, Dispatch, SetStateAction } from 'react';
|
||||
import { Rating } from 'react-daisyui';
|
||||
import { useForm, SubmitHandler } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
|
||||
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
|
||||
import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments';
|
||||
import FormError from '../ui/forms/FormError';
|
||||
import FormInfo from '../ui/forms/FormInfo';
|
||||
import FormLabel from '../ui/forms/FormLabel';
|
||||
import FormSegment from '../ui/forms/FormSegment';
|
||||
import FormTextArea from '../ui/forms/FormTextArea';
|
||||
|
||||
interface CommentCardDropdownProps {
|
||||
interface EditCommentBodyProps {
|
||||
comment: z.infer<typeof CommentQueryResult>;
|
||||
setInEditMode: Dispatch<SetStateAction<boolean>>;
|
||||
ref: ReturnType<typeof useInView>['ref'] | undefined;
|
||||
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
|
||||
|
||||
mutate: ReturnType<
|
||||
typeof useBeerPostComments | typeof useBreweryPostComments
|
||||
>['mutate'];
|
||||
handleDeleteRequest: (id: string) => Promise<void>;
|
||||
handleEditRequest: (
|
||||
id: string,
|
||||
data: z.infer<typeof CreateCommentValidationSchema>,
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
const EditCommentBody: FC<CommentCardDropdownProps> = ({
|
||||
const EditCommentBody: FC<EditCommentBodyProps> = ({
|
||||
comment,
|
||||
setInEditMode,
|
||||
ref,
|
||||
|
||||
mutate,
|
||||
handleDeleteRequest,
|
||||
handleEditRequest,
|
||||
}) => {
|
||||
const { register, handleSubmit, formState, setValue, watch } = useForm<
|
||||
z.infer<typeof CreateCommentValidationSchema>
|
||||
>({
|
||||
defaultValues: {
|
||||
content: comment.content,
|
||||
rating: comment.rating,
|
||||
},
|
||||
defaultValues: { content: comment.content, rating: comment.rating },
|
||||
resolver: zodResolver(CreateCommentValidationSchema),
|
||||
});
|
||||
|
||||
@@ -40,49 +46,24 @@ const EditCommentBody: FC<CommentCardDropdownProps> = ({
|
||||
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setIsDeleting(false);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleDelete = async () => {
|
||||
const onDelete = async () => {
|
||||
setIsDeleting(true);
|
||||
const response = await fetch(`/api/beer-comments/${comment.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete comment');
|
||||
}
|
||||
|
||||
await handleDeleteRequest(comment.id);
|
||||
await mutate();
|
||||
};
|
||||
|
||||
const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
|
||||
const onEdit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
|
||||
data,
|
||||
) => {
|
||||
const response = await fetch(`/api/beer-comments/${comment.id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
content: data.content,
|
||||
rating: data.rating,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to update comment');
|
||||
}
|
||||
|
||||
setInEditMode(true);
|
||||
await handleEditRequest(comment.id, data);
|
||||
await mutate();
|
||||
setInEditMode(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card-body animate-in fade-in-10" ref={ref}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
|
||||
<div className="card-body animate-in fade-in-10">
|
||||
<form onSubmit={handleSubmit(onEdit)} className="space-y-3">
|
||||
<div>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="content">Edit your comment</FormLabel>
|
||||
@@ -142,7 +123,7 @@ const EditCommentBody: FC<CommentCardDropdownProps> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="btn-xs btn lg:btn-sm"
|
||||
onClick={handleDelete}
|
||||
onClick={onDelete}
|
||||
disabled={isDeleting || formState.isSubmitting}
|
||||
>
|
||||
Delete
|
||||
|
||||
@@ -18,18 +18,42 @@ interface BeerPostCommentsSectionProps {
|
||||
const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => {
|
||||
const { user } = useContext(UserContext);
|
||||
const router = useRouter();
|
||||
const { id } = beerPost;
|
||||
|
||||
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
|
||||
const PAGE_SIZE = 4;
|
||||
|
||||
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
|
||||
useBeerPostComments({
|
||||
id,
|
||||
id: beerPost.id,
|
||||
pageNum,
|
||||
pageSize: PAGE_SIZE,
|
||||
});
|
||||
|
||||
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||
|
||||
async function handleDeleteRequest(id: string) {
|
||||
const response = await fetch(`/api/beer-comments/${id}`, { method: 'DELETE' });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete comment.');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEditRequest(
|
||||
id: string,
|
||||
data: { content: string; rating: number },
|
||||
) {
|
||||
const response = await fetch(`/api/beer-comments/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: data.content, rating: data.rating }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to update comment.');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full space-y-3" ref={commentSectionRef}>
|
||||
<div className="card bg-base-300">
|
||||
@@ -63,6 +87,8 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
|
||||
setSize={setSize}
|
||||
size={size}
|
||||
mutate={mutate}
|
||||
handleDeleteRequest={handleDeleteRequest}
|
||||
handleEditRequest={handleEditRequest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -104,6 +104,31 @@ const BreweryCommentsSection: FC<BreweryBeerSectionProps> = ({ breweryPost }) =>
|
||||
|
||||
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||
|
||||
const handleDeleteRequest = async (commentId: string) => {
|
||||
const response = await fetch(`/api/brewery-comments/${commentId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditRequest = async (
|
||||
commentId: string,
|
||||
data: z.infer<typeof CreateCommentValidationSchema>,
|
||||
) => {
|
||||
const response = await fetch(`/api/brewery-comments/${commentId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: data.content, rating: data.rating }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full space-y-3" ref={commentSectionRef}>
|
||||
<div className="card">
|
||||
@@ -136,6 +161,8 @@ const BreweryCommentsSection: FC<BreweryBeerSectionProps> = ({ breweryPost }) =>
|
||||
size={size}
|
||||
commentSectionRef={commentSectionRef}
|
||||
mutate={mutate}
|
||||
handleDeleteRequest={handleDeleteRequest}
|
||||
handleEditRequest={handleEditRequest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -29,6 +29,11 @@ interface CommentsComponentProps {
|
||||
mutate: ReturnType<
|
||||
typeof useBeerPostComments | typeof useBreweryPostComments
|
||||
>['mutate'];
|
||||
handleDeleteRequest: (id: string) => Promise<void>;
|
||||
handleEditRequest: (
|
||||
id: string,
|
||||
data: { content: string; rating: number },
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
const CommentsComponent: FC<CommentsComponentProps> = ({
|
||||
@@ -40,6 +45,8 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
|
||||
setSize,
|
||||
size,
|
||||
mutate,
|
||||
handleDeleteRequest,
|
||||
handleEditRequest,
|
||||
}) => {
|
||||
const { ref: penultimateCommentRef } = useInView({
|
||||
/**
|
||||
@@ -68,7 +75,12 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
|
||||
ref={isPenultimateComment ? penultimateCommentRef : undefined}
|
||||
key={comment.id}
|
||||
>
|
||||
<CommentCardBody comment={comment} mutate={mutate} />
|
||||
<CommentCardBody
|
||||
comment={comment}
|
||||
mutate={mutate}
|
||||
handleDeleteRequest={handleDeleteRequest}
|
||||
handleEditRequest={handleEditRequest}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
106
src/pages/api/brewery-comments/[id].ts
Normal file
106
src/pages/api/brewery-comments/[id].ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { UserExtendedNextApiRequest } from '@/config/auth/types';
|
||||
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
|
||||
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
|
||||
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiResponse } from 'next';
|
||||
import { createRouter, NextHandler } from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface DeleteCommentRequest extends UserExtendedNextApiRequest {
|
||||
query: { id: string };
|
||||
}
|
||||
|
||||
interface EditCommentRequest extends UserExtendedNextApiRequest {
|
||||
query: { id: string };
|
||||
body: z.infer<typeof CreateCommentValidationSchema>;
|
||||
}
|
||||
|
||||
const checkIfCommentOwner = async (
|
||||
req: DeleteCommentRequest | EditCommentRequest,
|
||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||
next: NextHandler,
|
||||
) => {
|
||||
const { id } = req.query;
|
||||
const user = req.user!;
|
||||
const comment = await DBClient.instance.breweryComment.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!comment) {
|
||||
throw new ServerError('Comment not found', 404);
|
||||
}
|
||||
|
||||
if (comment.postedById !== user.id) {
|
||||
throw new ServerError('You are not authorized to modify this comment', 403);
|
||||
}
|
||||
|
||||
await next();
|
||||
};
|
||||
|
||||
const editComment = async (
|
||||
req: EditCommentRequest,
|
||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||
) => {
|
||||
const { id } = req.query;
|
||||
|
||||
const updated = await DBClient.instance.breweryComment.update({
|
||||
where: { id },
|
||||
data: {
|
||||
content: req.body.content,
|
||||
rating: req.body.rating,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
message: 'Comment updated successfully',
|
||||
statusCode: 200,
|
||||
payload: updated,
|
||||
});
|
||||
};
|
||||
|
||||
const deleteComment = async (
|
||||
req: DeleteCommentRequest,
|
||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||
) => {
|
||||
const { id } = req.query;
|
||||
|
||||
await DBClient.instance.breweryComment.delete({ where: { id } });
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: 'Comment deleted successfully',
|
||||
statusCode: 200,
|
||||
});
|
||||
};
|
||||
|
||||
const router = createRouter<
|
||||
DeleteCommentRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>();
|
||||
|
||||
router
|
||||
.delete(
|
||||
validateRequest({ querySchema: z.object({ id: z.string().uuid() }) }),
|
||||
getCurrentUser,
|
||||
checkIfCommentOwner,
|
||||
deleteComment,
|
||||
)
|
||||
.put(
|
||||
validateRequest({
|
||||
querySchema: z.object({ id: z.string().uuid() }),
|
||||
bodySchema: CreateCommentValidationSchema,
|
||||
}),
|
||||
getCurrentUser,
|
||||
checkIfCommentOwner,
|
||||
editComment,
|
||||
);
|
||||
|
||||
const handler = router.handler(NextConnectOptions);
|
||||
export default handler;
|
||||
@@ -2,7 +2,7 @@ import { NextPage } from 'next';
|
||||
import Head from 'next/head';
|
||||
import React from 'react';
|
||||
|
||||
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
|
||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
||||
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||
import EditBeerPostForm from '@/components/EditBeerPostForm';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import CreateBeerPostForm from '@/components/CreateBeerPostForm';
|
||||
import FormPageLayout from '@/components/ui/forms/FormPageLayout';
|
||||
|
||||
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
|
||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
|
||||
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Spinner from '@/components/ui/Spinner';
|
||||
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
|
||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||
import UserContext from '@/contexts/userContext';
|
||||
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
|
||||
Reference in New Issue
Block a user