Get session user and add property

This commit is contained in:
Brad Traversy
2024-07-10 14:57:23 -04:00
parent 5417ba807d
commit c8d47bd4d4
6 changed files with 527 additions and 37 deletions
+63
View File
@@ -0,0 +1,63 @@
'use server';
import connectDB from '@/config/database';
import Property from '@/models/Property';
import { getSessionUser } from '@/utils/getSessionUser';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
async function addProperty(formData) {
await connectDB();
const sessionUser = await getSessionUser();
if (!sessionUser || !sessionUser.userId) {
throw new Error('User ID is required');
}
const { userId } = sessionUser;
// Access all values for amenities and images
const amenities = formData.getAll('amenities');
const images = formData
.getAll('images')
.filter((image) => image.name !== '') // Filter out empty names
.map((image) => image.name); // Extract only the names
// Create the propertyData object with embedded seller_info
const propertyData = {
type: formData.get('type'),
name: formData.get('name'),
description: formData.get('description'),
location: {
street: formData.get('location.street'),
city: formData.get('location.city'),
state: formData.get('location.state'),
zipcode: formData.get('location.zipcode'),
},
beds: formData.get('beds'),
baths: formData.get('baths'),
square_feet: formData.get('square_feet'),
amenities,
rates: {
weekly: formData.get('rates.weekly'),
monthly: formData.get('rates.monthly'),
nightly: formData.get('rates.nightly.'),
},
seller_info: {
name: formData.get('seller_info.name'),
email: formData.get('seller_info.email'),
phone: formData.get('seller_info.phone'),
},
images,
owner: userId,
};
const newProperty = new Property(propertyData);
await newProperty.save();
revalidatePath('/', 'layout');
redirect(`/properties/${newProperty._id}`);
}
export default addProperty;
+13 -3
View File
@@ -1,4 +1,14 @@
const AddPropertyPage = () => {
return <div>AddPropertyPage</div>;
import PropertyAddForm from '@/components/PropertyAddForm';
const PropertyAddPage = () => {
return (
<section className='bg-blue-50'>
<div className='container m-auto max-w-2xl py-24'>
<div className='bg-white px-6 py-8 mb-4 shadow-md rounded-md border m-4 md:m-0'>
<PropertyAddForm />
</div>
</div>
</section>
);
};
export default AddPropertyPage;
export default PropertyAddPage;