Delete property

This commit is contained in:
Brad Traversy
2024-07-11 16:57:33 -04:00
parent 4f9e8874d1
commit 91f038a33f
3 changed files with 70 additions and 1 deletions
+48
View File
@@ -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;
+1 -1
View File
@@ -216,7 +216,7 @@ const Navbar = () => {
<button
onClick={() => {
setIsProfileMenuOpen(false);
signOut();
signOut({ callbackUrl: '/' });
}}
className='block px-4 py-2 text-sm text-gray-700'
role='menuitem'
+21
View File
@@ -2,9 +2,29 @@
import { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import deleteProperty from '@/app/actions/deleteProperty';
const ProfileProperties = ({ properties: initialProperties }) => {
const [properties, setProperties] = useState(initialProperties);
const handleDeleteProperty = async (propertyId) => {
const confirmed = window.confirm(
'Are you sure you want to delete this property?'
);
if (!confirmed) return;
const deletePropertyById = deleteProperty.bind(null, propertyId);
await deletePropertyById();
const updatedProperties = properties.filter(
(property) => property._id !== propertyId
);
setProperties(updatedProperties);
};
return properties.map((property) => (
<div key={property._id} className='mb-10'>
<Link href={`/properties/${property._id}`}>
@@ -32,6 +52,7 @@ const ProfileProperties = ({ properties: initialProperties }) => {
Edit
</Link>
<button
onClick={() => handleDeleteProperty(property._id)}
className='bg-red-500 text-white px-3 py-2 rounded-md hover:bg-red-600'
type='button'
>