import * as mongoose from 'mongoose' import Booker from './booker' import Booking from './booking' let connectedPromise function connect() { if (connectedPromise) { return } connectedPromise = mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }) return connectedPromise } export async function getBookedDays() { await connect() 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() .sort() } 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() 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() }