From 3d29e76b9a7e6c6ba95dcb17adeedd753f274e34 Mon Sep 17 00:00:00 2001 From: Thomas Ruoff Date: Fri, 30 Oct 2020 23:29:04 +0100 Subject: [PATCH] populate days on save --- db/booking.ts | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/db/booking.ts b/db/booking.ts index 3e2608f..86ba83d 100644 --- a/db/booking.ts +++ b/db/booking.ts @@ -1,5 +1,6 @@ import * as mongoose from 'mongoose' import { v4 as uuidv4 } from 'uuid' +import { startOfDay } from 'date-fns' import { dateFormatBackend, getDays } from '../helpers/date' import { BillDocument } from './bill' import { BookerDocument } from './booker' @@ -54,6 +55,10 @@ const BookingSchema = new mongoose.Schema( get: dateFormatBackend, min: new Date(), }, + days: { + type: [String], + required: true, + }, status: { type: String, enum: Object.values(BOOKING_STATUS), @@ -71,27 +76,29 @@ const BookingSchema = new mongoose.Schema( } ) -BookingSchema.virtual('days').get(function () { - return getDays({ - startDate: new Date(this.startDate), - endDate: new Date(this.endDate), +BookingSchema.pre('save', function (next) { + const booking = this as BookingDocument + booking.days = getDays({ + startDate: new Date(booking.startDate), + endDate: new Date(booking.endDate), }) + next() }) BookingSchema.static('findBookedDays', async function (): Promise { - const bookings = await this.find( - { - status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] }, - $or: [ - { endDate: { $gt: new Date() } }, - { startDate: { $gt: new Date() } }, - ], - }, - 'startDate endDate' - ).exec() + const model = this as BookingModel + const bookedDays = await model + .find( + { + status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] }, + endDate: { $gt: startOfDay(new Date()) }, + }, + 'days' + ) + .exec() - return bookings - .map((booking: BookingDocument) => booking.days) + return bookedDays + .map((b) => b.days) .flat() .sort() })