From 341faa3bb080efcc71a775e93f9bde0f6abee1ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi?= Date: Sat, 4 Jan 2025 19:02:41 +0100 Subject: [PATCH] refactor: streamline time validation logic in ClassService --- src/modules/class/class.service.ts | 36 ++++++++++++++---------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/modules/class/class.service.ts b/src/modules/class/class.service.ts index fd0bcaa..33fb586 100644 --- a/src/modules/class/class.service.ts +++ b/src/modules/class/class.service.ts @@ -109,28 +109,26 @@ export class ClassService { ); const date = moment(createRoomClassDto.date); - const firstTimeDateStart = moment(date).set({ - hour: moment(createRoomClassDto.times[0].start, "HH:mm").hours(), - minute: moment( - createRoomClassDto.times[0].start, - "HH:mm", - ).minutes(), - }); - const firsTimeDateEnd = moment(date).set({ - hour: moment(createRoomClassDto.times[0].end, "HH:mm").hours(), - minute: moment(createRoomClassDto.times[0].end, "HH:mm").minutes(), - }); - // Check if start time is greater than end time - if (firstTimeDateStart.isAfter(firsTimeDateEnd)) - throw new HttpException( - "The end time must be greater than the start time", - 400, - ); + const firstTimeStart = createRoomClassDto.times.reduce((prev, current) => + moment(current.start, "HH:mm").isBefore(moment(prev.start, "HH:mm")) + ? current + : prev, + ); + const lastTimeEnd = createRoomClassDto.times.reduce((prev, current) => + moment(current.end, "HH:mm").isAfter(moment(prev.end, "HH:mm")) + ? current + : prev, + ); - if (moment().isAfter(firsTimeDateEnd)) + if ( + moment().isBefore( + moment(firstTimeStart.start, "HH:mm").subtract(5, "minutes"), + ) || + moment().isAfter(moment(lastTimeEnd.end, "HH:mm")) + ) throw new HttpException( - "The end time must be greater than the current time", + "Can't create a room for a class that has already ended", 400, );