Files
pfadi-bussle/pages/api/booking/[uuid]/index.ts
Thomas Ruoff 9f3b6bb2e1 remover booker, that's overdosed
It also brings the problem of consolidating bookers over multiple
bookings. The amount of data is not justifying having it in an own
entity
2021-06-21 23:21:23 +02:00

64 lines
1.6 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from 'next'
import { BookingDocument } from '../../../../db/booking'
import { BOOKING_STATUS } from '../../../../db/enums'
import { getBookingByUUID } from '../../../../db/index'
import withSession, { isAdminSession } from '../../../../lib/session'
export default withSession(async function userHandler(
req: NextApiRequest,
res: NextApiResponse
): Promise<void> {
const {
method,
query: { uuid: uuids },
} = req
const uuid = Array.isArray(uuids) ? uuids[0] : uuids
let booking: BookingDocument
switch (method) {
case 'PATCH':
booking = await getBookingByUUID(uuid)
if (!isAdminSession(req)) {
const deniedPropsForUser = Object.keys(req.body).filter(
(key) => key !== 'status'
)
if (deniedPropsForUser.length) {
res
.status(400)
.end(
`The following attributes cannot be changed: ${deniedPropsForUser.join(
', '
)}`
)
break
}
}
if (!Object.values(BOOKING_STATUS).includes(req.body.status)) {
res
.status(400)
.end(
`The attribute status can only be: ${Object.values(
BOOKING_STATUS
).join(', ')}`
)
break
}
booking.set(req.body)
try {
await booking.save()
res.status(200).json(booking.toJSON())
} catch (error) {
res.status(400).end(`Failed to save booking: ${error.message}`)
}
break
default:
res.setHeader('Allow', ['PATCH'])
res.status(405).end(`Method ${method} Not Allowed`)
}
})