Task: "Create Handle Recurring Bookings Api" Description: "Generate a Node.js…
- User
User: Task: "Create Handle Recurring Bookings Api" Description: "Generate a Node.js Handle Recurring Bookings Api with given dependenceis" Requirements: - Database: mongoose - Authentication: None specified - Output needed: Return only the function code as specified in dependencies - Dependencies: Create a function to manage recurring bookings. Export: exports.createRecurringBooking = async () => {...}, Accept parameters: startDate, endDate, frequency (e.g., weekly, monthly), roomId., Validate required fields: Ensure startDate, endDate, frequency, and roomId are provided., Use a scheduling library (e.g., node-cron) to generate recurring booking dates based on the frequency., Check availability for each recurring date using the checkAvailability function., Create bookings for each recurring date and link them to the same user or service., Respond with a success message containing the booking details for each occurrence., Handle errors like conflicting bookings, invalid parameters, or database issues. - Previous Code const mongoose = require('mongoose'); const Booking = require('./models/Booking'); // Assuming Booking model is in models/Booking.js
exports.checkAvailability = async (checkInDate, checkOutDate, roomId) => { // Validate required fields if (!checkInDate || !checkOutDate || !roomId) { throw new Error("Missing required parameters: checkInDate, checkOutDate, roomId are required."); }
// Convert dates to proper Date objects const checkIn = new Date(checkInDate); const checkOut = new Date(checkOutDate);
// Validate date formats if (isNaN(checkIn.getTime()) || isNaN(checkOut.getTime())) { throw new Error("Invalid date formats provided."); }
try { // Query the Booking model to find existing bookings within date range 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 { available: false, message: "Room/service is already booked for these dates." }; } // If no conflicting bookings found return { available: true, message: "Room/service is available for booking." };} catch (error) { // Handle database connection errors throw new Error("Database error: " + error.message); } };
exports.manageTimeSlots = async ({ date, serviceId, availableSlots }) => { // Validate required fields if (!date || !serviceId || !Array.isArray(availableSlots) || availableSlots.length === 0) { throw new Error("Missing required parameters: date, serviceId, and availableSlots are required."); }
- Assistant