Update: Refactor comments section to prop drill edit and delete handlers

This commit is contained in:
Aaron William Po
2023-05-06 00:09:02 -04:00
parent 2f8d7d6abb
commit 79e6ab8ba7
12 changed files with 241 additions and 70 deletions

View File

@@ -3,6 +3,7 @@ import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResul
import { FC, useState } from 'react'; import { FC, useState } from 'react';
import { useInView } from 'react-intersection-observer'; import { useInView } from 'react-intersection-observer';
import { z } from 'zod'; import { z } from 'zod';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import CommentContentBody from './CommentContentBody'; import CommentContentBody from './CommentContentBody';
import EditCommentBody from './EditCommentBody'; import EditCommentBody from './EditCommentBody';
@@ -10,20 +11,36 @@ interface CommentCardProps {
comment: z.infer<typeof CommentQueryResult>; comment: z.infer<typeof CommentQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate']; mutate: ReturnType<typeof useBeerPostComments>['mutate'];
ref?: ReturnType<typeof useInView>['ref']; 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); const [inEditMode, setInEditMode] = useState(false);
return !inEditMode ? ( return (
<CommentContentBody comment={comment} ref={ref} setInEditMode={setInEditMode} /> <div ref={ref}>
) : ( {!inEditMode ? (
<EditCommentBody <CommentContentBody comment={comment} setInEditMode={setInEditMode} />
comment={comment} ) : (
mutate={mutate} <EditCommentBody
setInEditMode={setInEditMode} comment={comment}
ref={ref} mutate={mutate}
/> setInEditMode={setInEditMode}
handleDeleteRequest={handleDeleteRequest}
handleEditRequest={handleEditRequest}
/>
)}
</div>
); );
}; };

View File

@@ -36,7 +36,14 @@ const CommentCardDropdown: FC<CommentCardDropdownProps> = ({
Edit Edit
</button> </button>
) : ( ) : (
<button>Report</button> <button
type="button"
onClick={() => {
alert('This feature is not yet implemented.');
}}
>
Report
</button>
)} )}
</li> </li>
</ul> </ul>

View File

@@ -4,26 +4,21 @@ import { format } from 'date-fns';
import { Dispatch, FC, SetStateAction, useContext } from 'react'; import { Dispatch, FC, SetStateAction, useContext } from 'react';
import { Link, Rating } from 'react-daisyui'; import { Link, Rating } from 'react-daisyui';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult'; import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod'; import { z } from 'zod';
import CommentCardDropdown from './CommentCardDropdown'; import CommentCardDropdown from './CommentCardDropdown';
interface CommentContentBodyProps { interface CommentContentBodyProps {
comment: z.infer<typeof CommentQueryResult>; comment: z.infer<typeof CommentQueryResult>;
ref: ReturnType<typeof useInView>['ref'] | undefined;
setInEditMode: Dispatch<SetStateAction<boolean>>; setInEditMode: Dispatch<SetStateAction<boolean>>;
} }
const CommentContentBody: FC<CommentContentBodyProps> = ({ const CommentContentBody: FC<CommentContentBodyProps> = ({ comment, setInEditMode }) => {
comment,
ref,
setInEditMode,
}) => {
const { user } = useContext(UserContext); const { user } = useContext(UserContext);
const timeDistance = useTimeDistance(new Date(comment.createdAt)); const timeDistance = useTimeDistance(new Date(comment.createdAt));
return ( 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 className="flex flex-row justify-between">
<div> <div>
<h3 className="font-semibold sm:text-2xl"> <h3 className="font-semibold sm:text-2xl">

View File

@@ -1,38 +1,44 @@
import { zodResolver } from '@hookform/resolvers/zod'; 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 { Rating } from 'react-daisyui';
import { useForm, SubmitHandler } from 'react-hook-form'; import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments'; import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult'; import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import { useInView } from 'react-intersection-observer';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema'; import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import useBreweryPostComments from '@/hooks/data-fetching/brewery-comments/useBreweryPostComments';
import FormError from '../ui/forms/FormError'; import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo'; import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel'; import FormLabel from '../ui/forms/FormLabel';
import FormSegment from '../ui/forms/FormSegment'; import FormSegment from '../ui/forms/FormSegment';
import FormTextArea from '../ui/forms/FormTextArea'; import FormTextArea from '../ui/forms/FormTextArea';
interface CommentCardDropdownProps { interface EditCommentBodyProps {
comment: z.infer<typeof CommentQueryResult>; comment: z.infer<typeof CommentQueryResult>;
setInEditMode: Dispatch<SetStateAction<boolean>>; 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, comment,
setInEditMode, setInEditMode,
ref,
mutate, mutate,
handleDeleteRequest,
handleEditRequest,
}) => { }) => {
const { register, handleSubmit, formState, setValue, watch } = useForm< const { register, handleSubmit, formState, setValue, watch } = useForm<
z.infer<typeof CreateCommentValidationSchema> z.infer<typeof CreateCommentValidationSchema>
>({ >({
defaultValues: { defaultValues: { content: comment.content, rating: comment.rating },
content: comment.content,
rating: comment.rating,
},
resolver: zodResolver(CreateCommentValidationSchema), resolver: zodResolver(CreateCommentValidationSchema),
}); });
@@ -40,49 +46,24 @@ const EditCommentBody: FC<CommentCardDropdownProps> = ({
const [isDeleting, setIsDeleting] = useState(false); const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => { const onDelete = async () => {
return () => {
setIsDeleting(false);
};
}, []);
const handleDelete = async () => {
setIsDeleting(true); setIsDeleting(true);
const response = await fetch(`/api/beer-comments/${comment.id}`, { await handleDeleteRequest(comment.id);
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete comment');
}
await mutate(); await mutate();
}; };
const onSubmit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async ( const onEdit: SubmitHandler<z.infer<typeof CreateCommentValidationSchema>> = async (
data, data,
) => { ) => {
const response = await fetch(`/api/beer-comments/${comment.id}`, { setInEditMode(true);
method: 'PUT', await handleEditRequest(comment.id, data);
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: data.content,
rating: data.rating,
}),
});
if (!response.ok) {
throw new Error('Failed to update comment');
}
await mutate(); await mutate();
setInEditMode(false); setInEditMode(false);
}; };
return ( return (
<div className="card-body animate-in fade-in-10" ref={ref}> <div className="card-body animate-in fade-in-10">
<form onSubmit={handleSubmit(onSubmit)} className="space-y-3"> <form onSubmit={handleSubmit(onEdit)} className="space-y-3">
<div> <div>
<FormInfo> <FormInfo>
<FormLabel htmlFor="content">Edit your comment</FormLabel> <FormLabel htmlFor="content">Edit your comment</FormLabel>
@@ -142,7 +123,7 @@ const EditCommentBody: FC<CommentCardDropdownProps> = ({
<button <button
type="button" type="button"
className="btn-xs btn lg:btn-sm" className="btn-xs btn lg:btn-sm"
onClick={handleDelete} onClick={onDelete}
disabled={isDeleting || formState.isSubmitting} disabled={isDeleting || formState.isSubmitting}
> >
Delete Delete

View File

@@ -18,18 +18,42 @@ interface BeerPostCommentsSectionProps {
const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => { const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => {
const { user } = useContext(UserContext); const { user } = useContext(UserContext);
const router = useRouter(); const router = useRouter();
const { id } = beerPost;
const pageNum = parseInt(router.query.comments_page as string, 10) || 1; const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
const PAGE_SIZE = 4; const PAGE_SIZE = 4;
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } = const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
useBeerPostComments({ useBeerPostComments({
id, id: beerPost.id,
pageNum, pageNum,
pageSize: PAGE_SIZE, pageSize: PAGE_SIZE,
}); });
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null); 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 ( return (
<div className="w-full space-y-3" ref={commentSectionRef}> <div className="w-full space-y-3" ref={commentSectionRef}>
<div className="card bg-base-300"> <div className="card bg-base-300">
@@ -63,6 +87,8 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
setSize={setSize} setSize={setSize}
size={size} size={size}
mutate={mutate} mutate={mutate}
handleDeleteRequest={handleDeleteRequest}
handleEditRequest={handleEditRequest}
/> />
) )
} }

View File

@@ -104,6 +104,31 @@ const BreweryCommentsSection: FC<BreweryBeerSectionProps> = ({ breweryPost }) =>
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null); 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 ( return (
<div className="w-full space-y-3" ref={commentSectionRef}> <div className="w-full space-y-3" ref={commentSectionRef}>
<div className="card"> <div className="card">
@@ -136,6 +161,8 @@ const BreweryCommentsSection: FC<BreweryBeerSectionProps> = ({ breweryPost }) =>
size={size} size={size}
commentSectionRef={commentSectionRef} commentSectionRef={commentSectionRef}
mutate={mutate} mutate={mutate}
handleDeleteRequest={handleDeleteRequest}
handleEditRequest={handleEditRequest}
/> />
) )
} }

View File

@@ -29,6 +29,11 @@ interface CommentsComponentProps {
mutate: ReturnType< mutate: ReturnType<
typeof useBeerPostComments | typeof useBreweryPostComments typeof useBeerPostComments | typeof useBreweryPostComments
>['mutate']; >['mutate'];
handleDeleteRequest: (id: string) => Promise<void>;
handleEditRequest: (
id: string,
data: { content: string; rating: number },
) => Promise<void>;
} }
const CommentsComponent: FC<CommentsComponentProps> = ({ const CommentsComponent: FC<CommentsComponentProps> = ({
@@ -40,6 +45,8 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
setSize, setSize,
size, size,
mutate, mutate,
handleDeleteRequest,
handleEditRequest,
}) => { }) => {
const { ref: penultimateCommentRef } = useInView({ const { ref: penultimateCommentRef } = useInView({
/** /**
@@ -68,7 +75,12 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
ref={isPenultimateComment ? penultimateCommentRef : undefined} ref={isPenultimateComment ? penultimateCommentRef : undefined}
key={comment.id} key={comment.id}
> >
<CommentCardBody comment={comment} mutate={mutate} /> <CommentCardBody
comment={comment}
mutate={mutate}
handleDeleteRequest={handleDeleteRequest}
handleEditRequest={handleEditRequest}
/>
</div> </div>
); );
})} })}

View 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;

View File

@@ -2,7 +2,7 @@ import { NextPage } from 'next';
import Head from 'next/head'; import Head from 'next/head';
import React from 'react'; import React from 'react';
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired'; import withPageAuthRequired from '@/util/withPageAuthRequired';
import getBeerPostById from '@/services/BeerPost/getBeerPostById'; import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult'; import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import EditBeerPostForm from '@/components/EditBeerPostForm'; import EditBeerPostForm from '@/components/EditBeerPostForm';

View File

@@ -1,7 +1,7 @@
import CreateBeerPostForm from '@/components/CreateBeerPostForm'; import CreateBeerPostForm from '@/components/CreateBeerPostForm';
import FormPageLayout from '@/components/ui/forms/FormPageLayout'; import FormPageLayout from '@/components/ui/forms/FormPageLayout';
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired'; import withPageAuthRequired from '@/util/withPageAuthRequired';
import DBClient from '@/prisma/DBClient'; import DBClient from '@/prisma/DBClient';
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts'; import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult'; import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';

View File

@@ -1,5 +1,5 @@
import Spinner from '@/components/ui/Spinner'; import Spinner from '@/components/ui/Spinner';
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired'; import withPageAuthRequired from '@/util/withPageAuthRequired';
import UserContext from '@/contexts/userContext'; import UserContext from '@/contexts/userContext';
import { GetServerSideProps, NextPage } from 'next'; import { GetServerSideProps, NextPage } from 'next';