User: Task: "Create Check Availability for Booking Api "
Description: "Generate a Node.js Check Availability for Booking Api with given dependenceis"
Requirements:
- Database: mongoose
- Output needed: Return only the function code as specified in dependencies
code
- Dependencies: Create a Api function to check real-time availability. Export: exports.checkAvailability = async () => {...},
Accept data from user: checkInDate, checkOutDate, roomId (or serviceId).,
Validate required fields: Ensure checkInDate, checkOutDate, and roomId are provided.,
Query the Booking model to check for any existing bookings during the specified date range.,
Ensure no double booking occurs for the same room or service in the selected date range.,
If the room or service is available, respond with a success message and availability status.,
If unavailable, respond with an error message indicating double booking.,
Handle errors like missing or invalid parameters, database connection errors.
code
- Supporting data
Please generate the code for this task, following the instructions and including comments for clarity.
While creating router for specifict file your have to read supporing file data and create for that
User:
Assistant:
Assistant
Certainly! Below is the code for a Node.js API function using Mongoose to check real-time availability for bookings. This function validates inputs, interacts with a booking model to check availability, and returns appropriate responses.
Before using this function, ensure you have set up a Mongoose model for Booking and have connected your Node.js application to a MongoDB database.
javascript
const mongoose = require('mongoose');
const Booking = require('./models/Booking'); // Adjust the path as per your project structure
// Function to check real-time availability
exports.checkAvailability = async (req, res) => {
try {
const { checkInDate, checkOutDate, roomId } = req.body;
// Validate required fields
if (!checkInDate || !checkOutDate || !roomId) {
return res.status(400).json({ message: 'Missing required parameters.' });
}
const checkIn = new Date(checkInDate);
const checkOut = new Date(checkOutDate);
// Ensure dates are valid
if (isNaN(checkIn.getTime()) || isNaN(checkOut.getTime()) || checkIn >= checkOut) {
return res.status(400).json({ message: 'Invalid date range.' });
}
// Query the Booking model to check for existing bookings
const existingBookings = await Booking.find({
roomId: roomId,
$or: [
{ checkInDate: { $lt: checkOut, $gte: checkIn } },
{ checkOutDate: { $gt: checkIn, $lte: checkOut } },
{ checkInDate: { $lte: checkIn }, checkOutDate: { $gte: checkOut } }
]
});
// Ensure no double booking
if (existingBookings.length > 0) {
return res.status(409).json({ message: 'Double booking detected: The room/service is not available for the selected date range.' });
}
// If room/service is available
res.status(200).json({ message: 'Room/service is available for the selected date range.', available: true });
} catch (error) {
// Handle database connection errors and others
res.status(500).json({ message: 'Internal server error.', error: error.message });
}
};
Key Points:
Dependencies: Mongoose and your Booking model are used. Make sure these dependencies are properly set up in your project.
Validation: The function checks if all the required parameters are present and if the date range is valid before querying the database.
Date Range Query: It uses an $or condition to check overlapping bookings to prevent double booking.
Error Handling: It handles missing parameters, invalid dates, and server errors gracefully.
Export: The function is exported using exports.checkAvailability to be used in your application's routing logic.
Ensure you add appropriate routes to your server to handle requests to this function. Example: