populate days on save

This commit is contained in:
Thomas Ruoff
2020-10-30 23:29:04 +01:00
parent 6d290cd6e9
commit 3d29e76b9a

View File

@@ -1,5 +1,6 @@
import * as mongoose from 'mongoose' import * as mongoose from 'mongoose'
import { v4 as uuidv4 } from 'uuid' import { v4 as uuidv4 } from 'uuid'
import { startOfDay } from 'date-fns'
import { dateFormatBackend, getDays } from '../helpers/date' import { dateFormatBackend, getDays } from '../helpers/date'
import { BillDocument } from './bill' import { BillDocument } from './bill'
import { BookerDocument } from './booker' import { BookerDocument } from './booker'
@@ -54,6 +55,10 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
get: dateFormatBackend, get: dateFormatBackend,
min: new Date(), min: new Date(),
}, },
days: {
type: [String],
required: true,
},
status: { status: {
type: String, type: String,
enum: Object.values(BOOKING_STATUS), enum: Object.values(BOOKING_STATUS),
@@ -71,27 +76,29 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
} }
) )
BookingSchema.virtual('days').get(function () { BookingSchema.pre('save', function (next) {
return getDays({ const booking = this as BookingDocument
startDate: new Date(this.startDate), booking.days = getDays({
endDate: new Date(this.endDate), startDate: new Date(booking.startDate),
endDate: new Date(booking.endDate),
}) })
next()
}) })
BookingSchema.static('findBookedDays', async function (): Promise<string[]> { BookingSchema.static('findBookedDays', async function (): Promise<string[]> {
const bookings = await this.find( const model = this as BookingModel
{ const bookedDays = await model
status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] }, .find(
$or: [ {
{ endDate: { $gt: new Date() } }, status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] },
{ startDate: { $gt: new Date() } }, endDate: { $gt: startOfDay(new Date()) },
], },
}, 'days'
'startDate endDate' )
).exec() .exec()
return bookings return bookedDays
.map((booking: BookingDocument) => booking.days) .map((b) => b.days)
.flat() .flat()
.sort() .sort()
}) })