mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Get basic editing functionality for beer comments
This commit is contained in:
@@ -2,14 +2,22 @@ import UserContext from '@/contexts/userContext';
|
|||||||
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
import useBeerPostComments from '@/hooks/useBeerPostComments';
|
||||||
import useTimeDistance from '@/hooks/useTimeDistance';
|
import useTimeDistance from '@/hooks/useTimeDistance';
|
||||||
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
||||||
|
import BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import format from 'date-fns/format';
|
import format from 'date-fns/format';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { FC, useContext } from 'react';
|
import { Dispatch, FC, SetStateAction, useContext, useEffect, useState } from 'react';
|
||||||
import { Rating } from 'react-daisyui';
|
import { Rating } from 'react-daisyui';
|
||||||
|
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||||
|
|
||||||
import { FaEllipsisH } from 'react-icons/fa';
|
import { FaEllipsisH } from 'react-icons/fa';
|
||||||
import { useInView } from 'react-intersection-observer';
|
import { useInView } from 'react-intersection-observer';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
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 CommentCardProps {
|
interface CommentCardProps {
|
||||||
comment: z.infer<typeof BeerCommentQueryResult>;
|
comment: z.infer<typeof BeerCommentQueryResult>;
|
||||||
@@ -17,25 +25,21 @@ interface CommentCardProps {
|
|||||||
ref?: ReturnType<typeof useInView>['ref'];
|
ref?: ReturnType<typeof useInView>['ref'];
|
||||||
}
|
}
|
||||||
|
|
||||||
const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
|
interface CommentCardDropdownProps extends CommentCardProps {
|
||||||
|
inEditMode: boolean;
|
||||||
|
setInEditMode: Dispatch<SetStateAction<boolean>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CommentCardDropdown: FC<CommentCardDropdownProps> = ({
|
||||||
|
comment,
|
||||||
|
setInEditMode,
|
||||||
|
}) => {
|
||||||
const { user } = useContext(UserContext);
|
const { user } = useContext(UserContext);
|
||||||
|
|
||||||
const isCommentOwner = user?.id === comment.postedBy.id;
|
const isCommentOwner = user?.id === comment.postedBy.id;
|
||||||
|
|
||||||
const handleDelete = async () => {
|
|
||||||
const response = await fetch(`/api/beer-comments/${comment.id}`, {
|
|
||||||
method: 'DELETE',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Failed to delete comment');
|
|
||||||
}
|
|
||||||
|
|
||||||
await mutate();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="dropdown dropdown-end">
|
<div className="dropdown-end dropdown">
|
||||||
<label tabIndex={0} className="btn-ghost btn-sm btn m-1">
|
<label tabIndex={0} className="btn-ghost btn-sm btn m-1">
|
||||||
<FaEllipsisH />
|
<FaEllipsisH />
|
||||||
</label>
|
</label>
|
||||||
@@ -46,9 +50,13 @@ const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
|
|||||||
<li>
|
<li>
|
||||||
{isCommentOwner ? (
|
{isCommentOwner ? (
|
||||||
<>
|
<>
|
||||||
<button type="button">Edit</button>
|
<button
|
||||||
<button type="button" onClick={handleDelete}>
|
type="button"
|
||||||
Delete
|
onClick={() => {
|
||||||
|
setInEditMode(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Edit
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -60,9 +68,157 @@ const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
|
const EditCommentBody: FC<CommentCardDropdownProps> = ({
|
||||||
const { user } = useContext(UserContext);
|
comment,
|
||||||
|
setInEditMode,
|
||||||
|
ref,
|
||||||
|
mutate,
|
||||||
|
}) => {
|
||||||
|
const { register, handleSubmit, formState, setValue, watch } = useForm<
|
||||||
|
z.infer<typeof BeerCommentValidationSchema>
|
||||||
|
>({
|
||||||
|
defaultValues: {
|
||||||
|
content: comment.content,
|
||||||
|
rating: comment.rating,
|
||||||
|
},
|
||||||
|
resolver: zodResolver(BeerCommentValidationSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { errors } = formState;
|
||||||
|
|
||||||
|
const [isDeleting, setIsDeleting] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
setIsDeleting(false);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDelete = 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 mutate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSubmit: SubmitHandler<z.infer<typeof BeerCommentValidationSchema>> = 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="content">Edit your comment</FormLabel>
|
||||||
|
<FormError>{errors.content?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<FormSegment>
|
||||||
|
<FormTextArea
|
||||||
|
id="content"
|
||||||
|
formValidationSchema={register('content')}
|
||||||
|
placeholder="Comment"
|
||||||
|
rows={2}
|
||||||
|
error={!!errors.content?.message}
|
||||||
|
disabled={formState.isSubmitting || isDeleting}
|
||||||
|
/>
|
||||||
|
</FormSegment>
|
||||||
|
<div className="flex flex-row items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<FormInfo>
|
||||||
|
<FormLabel htmlFor="rating">Change your rating</FormLabel>
|
||||||
|
<FormError>{errors.rating?.message}</FormError>
|
||||||
|
</FormInfo>
|
||||||
|
<Rating
|
||||||
|
value={watch('rating')}
|
||||||
|
onChange={(value) => {
|
||||||
|
setValue('rating', value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{Array.from({ length: 5 }).map((val, index) => (
|
||||||
|
<Rating.Item
|
||||||
|
name="rating-1"
|
||||||
|
className="mask mask-star cursor-default"
|
||||||
|
disabled={formState.isSubmitting || isDeleting}
|
||||||
|
aria-disabled={formState.isSubmitting || isDeleting}
|
||||||
|
key={index}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Rating>
|
||||||
|
</div>
|
||||||
|
<div className="flex">
|
||||||
|
<div className="w-4/12">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={formState.isSubmitting || isDeleting}
|
||||||
|
className="btn-ghost btn-sm btn w-full"
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-4/12">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-ghost btn-sm btn w-full"
|
||||||
|
disabled={formState.isSubmitting || isDeleting}
|
||||||
|
onClick={() => {
|
||||||
|
setInEditMode(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-4/12">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-ghost btn-sm btn w-full"
|
||||||
|
onClick={handleDelete}
|
||||||
|
disabled={isDeleting || formState.isSubmitting}
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const CommentContentBody: FC<CommentCardDropdownProps> = ({
|
||||||
|
comment,
|
||||||
|
ref,
|
||||||
|
mutate,
|
||||||
|
inEditMode,
|
||||||
|
setInEditMode,
|
||||||
|
}) => {
|
||||||
|
const { user } = useContext(UserContext);
|
||||||
const timeDistance = useTimeDistance(new Date(comment.createdAt));
|
const timeDistance = useTimeDistance(new Date(comment.createdAt));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -86,7 +242,14 @@ const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
|
|||||||
</h4>
|
</h4>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{user && <CommentCardDropdown comment={comment} mutate={mutate} />}
|
{user && (
|
||||||
|
<CommentCardDropdown
|
||||||
|
comment={comment}
|
||||||
|
mutate={mutate}
|
||||||
|
inEditMode={inEditMode}
|
||||||
|
setInEditMode={setInEditMode}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
@@ -107,4 +270,26 @@ const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
|
||||||
|
const [inEditMode, setInEditMode] = useState(false);
|
||||||
|
|
||||||
|
return !inEditMode ? (
|
||||||
|
<CommentContentBody
|
||||||
|
comment={comment}
|
||||||
|
inEditMode={inEditMode}
|
||||||
|
mutate={mutate}
|
||||||
|
ref={ref}
|
||||||
|
setInEditMode={setInEditMode}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<EditCommentBody
|
||||||
|
comment={comment}
|
||||||
|
inEditMode={inEditMode}
|
||||||
|
mutate={mutate}
|
||||||
|
ref={ref}
|
||||||
|
setInEditMode={setInEditMode}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export default CommentCardBody;
|
export default CommentCardBody;
|
||||||
|
|||||||
107
src/pages/api/beer-comments/[id].ts
Normal file
107
src/pages/api/beer-comments/[id].ts
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
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 BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
|
||||||
|
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 BeerCommentValidationSchema>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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.beerComment.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.beerComment.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.beerComment.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: BeerCommentValidationSchema,
|
||||||
|
}),
|
||||||
|
getCurrentUser,
|
||||||
|
checkIfCommentOwner,
|
||||||
|
editComment,
|
||||||
|
);
|
||||||
|
|
||||||
|
const handler = router.handler(NextConnectOptions);
|
||||||
|
export default handler;
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
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 APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
|
||||||
import { NextApiResponse } from 'next';
|
|
||||||
import { createRouter } from 'next-connect';
|
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
interface DeleteCommentRequest extends UserExtendedNextApiRequest {
|
|
||||||
query: { id: string };
|
|
||||||
}
|
|
||||||
|
|
||||||
const deleteComment = async (
|
|
||||||
req: DeleteCommentRequest,
|
|
||||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
|
||||||
) => {
|
|
||||||
const { id } = req.query;
|
|
||||||
const user = req.user!;
|
|
||||||
|
|
||||||
const comment = await DBClient.instance.beerComment.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 delete this comment', 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
await DBClient.instance.beerComment.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,
|
|
||||||
deleteComment,
|
|
||||||
);
|
|
||||||
|
|
||||||
const handler = router.handler(NextConnectOptions);
|
|
||||||
export default handler;
|
|
||||||
Reference in New Issue
Block a user