69 lines
1.6 KiB
JavaScript
69 lines
1.6 KiB
JavaScript
import Event from '../../../models/event';
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const id = getRouterParam(event, 'id');
|
|
const body = await readBody(event);
|
|
const { email } = body;
|
|
|
|
if (!email) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Email is required'
|
|
});
|
|
}
|
|
|
|
try {
|
|
// Check if id is a valid ObjectId or treat as slug
|
|
const isObjectId = /^[0-9a-fA-F]{24}$/.test(id);
|
|
const query = isObjectId
|
|
? { $or: [{ _id: id }, { slug: id }] }
|
|
: { slug: id };
|
|
|
|
const eventDoc = await Event.findOne(query);
|
|
|
|
if (!eventDoc) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: 'Event not found'
|
|
});
|
|
}
|
|
|
|
// Find the registration index
|
|
const registrationIndex = eventDoc.registrations.findIndex(
|
|
registration => registration.email.toLowerCase() === email.toLowerCase()
|
|
);
|
|
|
|
if (registrationIndex === -1) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: 'Registration not found'
|
|
});
|
|
}
|
|
|
|
// Remove the registration
|
|
eventDoc.registrations.splice(registrationIndex, 1);
|
|
|
|
// Update registered count
|
|
eventDoc.registeredCount = eventDoc.registrations.length;
|
|
|
|
await eventDoc.save();
|
|
|
|
return {
|
|
success: true,
|
|
message: 'Registration cancelled successfully',
|
|
registeredCount: eventDoc.registeredCount
|
|
};
|
|
} catch (error) {
|
|
console.error('Error cancelling registration:', error);
|
|
|
|
// Re-throw known errors
|
|
if (error.statusCode) {
|
|
throw error;
|
|
}
|
|
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Failed to cancel registration'
|
|
});
|
|
}
|
|
});
|