mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 06:27:11 +01:00
67 lines
1.7 KiB
JavaScript
67 lines
1.7 KiB
JavaScript
import mongoose from 'mongoose'
|
|
import { BookingSchema, BookerSchema } from './schema'
|
|
|
|
mongoose.connect(process.env.MONGO_URI, {
|
|
useNewUrlParser: true,
|
|
useUnifiedTopology: true,
|
|
connectTimeoutMS: 1000,
|
|
serverSelectionTimeoutMS: 5000,
|
|
})
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
mongoose.modelNames().includes('Booker') && mongoose.deleteModel('Booker')
|
|
mongoose.modelNames().includes('Booking') && mongoose.deleteModel('Booking')
|
|
}
|
|
|
|
export const Booker =
|
|
mongoose.models.Booker || mongoose.model('Booker', BookerSchema)
|
|
export const Booking =
|
|
mongoose.models.Booking || mongoose.model('Booking', BookingSchema)
|
|
|
|
export async function getBookedDays() {
|
|
const bookings = await Booking.find(
|
|
{
|
|
status: { $ne: 'rejected' },
|
|
$or: [
|
|
{ endDate: { $gt: new Date() } },
|
|
{ startDate: { $gt: new Date() } },
|
|
],
|
|
},
|
|
'startDate endDate'
|
|
).exec()
|
|
|
|
return bookings.map((booking) => booking.days).flat()
|
|
}
|
|
|
|
export async function createBooking({
|
|
startDate,
|
|
endDate,
|
|
purpose,
|
|
org,
|
|
destination,
|
|
name,
|
|
email,
|
|
street,
|
|
zip,
|
|
city,
|
|
}) {
|
|
const booking = new Booking({ startDate, endDate, purpose, org, destination })
|
|
const bookedDays = await getBookedDays()
|
|
|
|
if (booking.days.some((day) => bookedDays.includes(day))) {
|
|
throw new mongoose.Error.ValidationError(booking)
|
|
}
|
|
|
|
const ignoreCaseEmailMatcher = new RegExp(email, 'i')
|
|
let booker = await Booker.findOne({ email: ignoreCaseEmailMatcher }).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()
|
|
}
|