ghostguild-org/server/api/admin/events/[id].put.js

79 lines
No EOL
2.4 KiB
JavaScript

import Event from '../../../models/event.js'
import { connectDB } from '../../../utils/mongoose.js'
import jwt from 'jsonwebtoken'
export default defineEventHandler(async (event) => {
try {
// TODO: Temporarily disabled auth for testing - enable when authentication is set up
// const token = getCookie(event, 'auth-token') || getHeader(event, 'authorization')?.replace('Bearer ', '')
// if (!token) {
// throw createError({
// statusCode: 401,
// statusMessage: 'Authentication required'
// })
// }
// const config = useRuntimeConfig()
// const decoded = jwt.verify(token, config.jwtSecret)
const eventId = getRouterParam(event, 'id')
const body = await readBody(event)
// Validate required fields
if (!body.title || !body.description || !body.startDate || !body.endDate) {
throw createError({
statusCode: 400,
statusMessage: 'Missing required fields'
})
}
await connectDB()
const updateData = {
...body,
startDate: new Date(body.startDate),
endDate: new Date(body.endDate),
registrationDeadline: body.registrationDeadline ? new Date(body.registrationDeadline) : null,
updatedAt: new Date()
}
// Handle ticket data
if (body.tickets) {
updateData.tickets = {
enabled: body.tickets.enabled || false,
public: {
available: body.tickets.public?.available || false,
name: body.tickets.public?.name || 'Public Ticket',
description: body.tickets.public?.description || '',
price: body.tickets.public?.price || 0,
quantity: body.tickets.public?.quantity || null,
sold: body.tickets.public?.sold || 0,
earlyBirdPrice: body.tickets.public?.earlyBirdPrice || null,
earlyBirdDeadline: body.tickets.public?.earlyBirdDeadline ? new Date(body.tickets.public.earlyBirdDeadline) : null
}
}
}
const updatedEvent = await Event.findByIdAndUpdate(
eventId,
updateData,
{ new: true, runValidators: true }
)
if (!updatedEvent) {
throw createError({
statusCode: 404,
statusMessage: 'Event not found'
})
}
return updatedEvent
} catch (error) {
console.error('Error updating event:', error)
throw createError({
statusCode: 500,
statusMessage: error.message || 'Failed to update event'
})
}
})