From 91f038a33fe11a512a9091b321b3780303ae6d3f Mon Sep 17 00:00:00 2001 From: Brad Traversy Date: Thu, 11 Jul 2024 16:57:33 -0400 Subject: [PATCH] Delete property --- app/actions/deleteProperty.js | 48 ++++++++++++++++++++++++++++++++ components/Navbar.jsx | 2 +- components/ProfileProperties.jsx | 21 ++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 app/actions/deleteProperty.js diff --git a/app/actions/deleteProperty.js b/app/actions/deleteProperty.js new file mode 100644 index 0000000..b57cdb2 --- /dev/null +++ b/app/actions/deleteProperty.js @@ -0,0 +1,48 @@ +'use server'; +import cloudinary from '@/config/cloudinary'; +import connectDB from '@/config/database'; +import Property from '@/models/Property'; +import { getSessionUser } from '@/utils/getSessionUser'; +import { revalidatePath } from 'next/cache'; + +async function deleteProperty(propertyId) { + const sessionUser = await getSessionUser(); + + // Check for session + if (!sessionUser || !sessionUser.userId) { + throw new Error('User ID is required'); + } + + const { userId } = sessionUser; + + await connectDB(); + + const property = await Property.findById(propertyId); + + if (!property) throw new Error('Property Not Found'); + + // Verify ownership + if (property.owner.toString() !== userId) { + throw new Error('Unauthorized'); + } + + // extract public id's from image url in DB + const publicIds = property.images.map((imageUrl) => { + const parts = imageUrl.split('/'); + return parts.at(-1).split('.').at(0); + }); + + // Delete images from Cloudinary + if (publicIds.length > 0) { + for (let publicId of publicIds) { + await cloudinary.uploader.destroy('propertypulse/' + publicId); + } + } + + // Proceed with property deletion + await property.deleteOne(); + + revalidatePath('/', 'layout'); +} + +export default deleteProperty; diff --git a/components/Navbar.jsx b/components/Navbar.jsx index 4871b9b..5c65df3 100644 --- a/components/Navbar.jsx +++ b/components/Navbar.jsx @@ -216,7 +216,7 @@ const Navbar = () => {