Currently, I'm immersed in a Next.js project where the main goal is to eliminate a post by its unique id
. To carry out this task efficiently, I make use of Prisma as my ORM and Zod for data validation. The crux of the operation involves the client-side component dispatching a DELETE request to an API route on my server, alongside including the specific id
of the post earmarked for deletion within the request body.
Let me walk you through my client-side approach when it comes to managing deletions:
const handleDelete = async () => {
if (!post?.id) return;
try {
await axios.delete(`/api/subreddit/post/delete/`, {
data: { postId: post.id },
});
toast({
title: "Success",
description: "Post was deleted successfully",
});
router.refresh(); // Refresh the page or redirect the user.
} catch (error) {
console.log(error); // Record any encountered errors
return toast({
title: 'Something went wrong.',
description: "Post wasn't deleted successfully. Please try again.",
variant: 'destructive',
})
}
};
To complement this, my server-side mechanism is structured like so:
export async function DELETE(req: Request) {
try {
const body = await req.json();
const { postId } = z.object({
postId: z.string(),
}).parse(body);
const session = await getAuthSession();
if (!session?.user) {
return new Response("Unauthorized", { status: 401 });
}
const post = await db.post.findUnique({
where: {
id: postId,
},
});
if (!post) {
return new Response("Post not found", { status: 404 });
}
if (post.authorId !== session.user.id) {
return new Response("You do not have permission to delete this post", { status: 403 });
}
await db.post.delete({
where: {
id: postId,
},
});
return new Response("Post Deleted");
} catch (error:any) {
console.log('Error when deleting post:', error.message);
if (error instanceof z.ZodError) {
return new Response(error.message, { status: 400 });
}
return new Response(
"Could not delete post at this time. Please try later",
{ status: 500 }
);
}
}
An issue I encounter while endeavoring to erase a post manifests in the form of:
[
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"postId"
],
"message": "Required"
}
]
This particular hiccup alludes to the fact that postId
emerges as undefined
. The mystifying aspect of this dilemma lies in the fact that, indeed, a valid postId
enters the fray via my client-side DELETE request. Any insights or suggestions on how to rectify this anomaly would be genuinely appreciated!
Attempts were made to peruse the request logs and pinpoint the root cause of the matter, unfortunately, they did not yield successful results.