User: Task: "Create Manage Time Slots"
Description: "Generate a Node.js Manage Time Slots Api with given dependenceis"
Requirements:
- Database: mongoose
- Output needed: Return only the function code as specified in dependencies
code
- Dependencies: Create a Api to manage time slots for a specific date and service. Export: exports.manageTimeSlots = async () => {...},
Accept data from user: date, serviceId, availableSlots (array of time slots).,
Validate required fields: Ensure date, serviceId, and availableSlots are provided.,
Use the TimeSlot model to create or update available time slots for the service on the specified date.,
Ensure that time slots do not overlap with other existing bookings for the service.,
Allow the admin to define time intervals (e.g., 30 mins, 1 hour).,
Respond to user with a success message indicating available time slots.,
Handle errors like invalid date, overlapping time slots, or database issues.
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
To create a Node.js API that manages time slots using Mongoose, we'll follow your task description and requirements to generate the code. Below is a function implementation that handles creating or updating available time slots for a specific service on a given date.
Prerequisites:
Mongoose should be set up and connected to your MongoDB instance.
A TimeSlot model should be defined with the necessary schema.
Model Definition:
First, make sure you have a TimeSlot model defined like so (for example purposes):
const TimeSlot = require('./models/TimeSlot'); // Import your TimeSlot model
exports.manageTimeSlots = async ({ date, serviceId, availableSlots }) => {
try {
// Validate required fields
if (!date || !serviceId || !availableSlots || !Array.isArray(availableSlots)) {
throw new Error('Date, serviceId, and availableSlots are required.');
}
// Convert date to Date object for consistency in querying
const parsedDate = new Date(date);
if (isNaN(parsedDate)) {
throw new Error('Invalid date format.');
}
// Ensure no overlapping time slots with existing bookings
const existingSlots = await TimeSlot.findOne({ date: parsedDate, serviceId });
if (existingSlots) {
const overlap = existingSlots.availableSlots.some(slot => availableSlots.includes(slot));
if (overlap) {
throw new Error('Some time slots are overlapping with existing bookings.');
}
// Update existing time slots
existingSlots.availableSlots = [...new Set([...existingSlots.availableSlots, ...availableSlots])];
await existingSlots.save();
} else {
// Create new time slots
const newTimeSlot = new TimeSlot({
date: parsedDate,
serviceId,
availableSlots,
});
await newTimeSlot.save();
}
return { message: 'Available time slots have been successfully updated.' };
} catch (error) {
console.error('Error managing time slots:', error.message);
throw new Error(`Failed to manage time slots: ${error.message}`);
}
};
// Example usage would involve setting up an Express endpoint or similar
Explanation:
Validation: The function checks if date, serviceId, and availableSlots are provided.
Date Parsing: Converts the input date string into a Date object.
Check for Overlapping Slots: It verifies that no time slots overlap with existing slots for the same service and date.
Updating or Creating Records: Updates existing records or creates new ones depending on the presence of existing time slots.
Error Handling: Catches and logs errors, and returns meaningful error messages.
Integration:
Integrate this function within an Express endpoint to handle API requests: