Files
pfadi-bussle/db/index.ts
2020-09-18 00:53:10 +02:00

85 lines
1.9 KiB
TypeScript

import * as mongoose from 'mongoose'
import Booker from './booker'
import Booking from './booking'
import { dateFormatFrontend } from '../helpers/date'
import { BOOKING_STATUS } from './bookingStatus'
let connectedPromise: Promise<typeof mongoose>
function connect() {
if (connectedPromise) {
return
}
connectedPromise = mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
return connectedPromise
}
export async function getBookedDays() {
await connect()
return Booking.findBookedDays()
}
export async function getBookingByUUID(uuid: string) {
await connect()
const booking = await Booking.findOne({ uuid })
return booking?.populate('booker').execPopulate()
}
export async function getBookings() {
await connect()
const bookings = await Booking.find({
status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] },
})
// populate?
return bookings
}
export async function createBooking({
startDate,
endDate,
purpose,
org,
destination,
name,
email,
street,
zip,
city,
}) {
await connect()
const booking = new Booking({ startDate, endDate, purpose, org, destination })
const bookedDays = await getBookedDays()
const doubleBookedDays = booking.days.filter((day: string) =>
bookedDays.includes(day)
)
if (doubleBookedDays.length) {
const error = new mongoose.Error.ValidationError(booking)
error.addError(
'days',
new mongoose.Error.ValidatorError({
message: `${doubleBookedDays
.map(dateFormatFrontend)
.join(', ')} schon gebucht`,
})
)
throw error
}
let booker = await Booker.findOne({ email }).exec()
if (!booker) {
booker = new Booker({ name, email, street, zip, city })
await booker.save()
}
booking.booker = booker._id
await booking.save()
await booking.populate('booker').execPopulate()
return booking.toJSON()
}