2023-05-26 15:43:14 -05:00
|
|
|
import { Process, Processor } from '@nestjs/bull'
|
2023-06-29 10:32:09 +02:00
|
|
|
import { Inject } from '@nestjs/common'
|
2023-05-26 15:43:14 -05:00
|
|
|
import { Job } from 'bull'
|
|
|
|
|
import { instanceToPlain, plainToInstance } from 'class-transformer'
|
2023-06-29 10:32:09 +02:00
|
|
|
|
|
|
|
|
import { LoggerService } from '../logger/service'
|
2023-07-28 19:50:04 +02:00
|
|
|
import {
|
|
|
|
|
BaanReserverenService,
|
|
|
|
|
NoCourtAvailableError,
|
|
|
|
|
} from '../runner/baanreserveren/service'
|
2023-05-26 15:43:14 -05:00
|
|
|
import { RESERVATIONS_QUEUE_NAME } from './config'
|
|
|
|
|
import { Reservation } from './entity'
|
|
|
|
|
|
|
|
|
|
@Processor(RESERVATIONS_QUEUE_NAME)
|
|
|
|
|
export class ReservationsWorker {
|
2023-06-27 16:06:19 +02:00
|
|
|
constructor(
|
|
|
|
|
@Inject(BaanReserverenService)
|
|
|
|
|
private readonly brService: BaanReserverenService,
|
2023-05-26 15:43:14 -05:00
|
|
|
|
2023-06-27 16:06:19 +02:00
|
|
|
@Inject(LoggerService)
|
|
|
|
|
private readonly logger: LoggerService,
|
|
|
|
|
) {}
|
2023-05-26 15:43:14 -05:00
|
|
|
|
2023-06-27 16:06:19 +02:00
|
|
|
@Process()
|
|
|
|
|
async handleReservationJob(job: Job<Reservation>) {
|
|
|
|
|
const reservation = plainToInstance(Reservation, job.data, {
|
|
|
|
|
groups: ['password'],
|
|
|
|
|
})
|
|
|
|
|
this.logger.log('Handling reservation', {
|
|
|
|
|
reservation: instanceToPlain(reservation),
|
|
|
|
|
})
|
|
|
|
|
await this.performReservation(reservation)
|
|
|
|
|
}
|
2023-05-26 15:43:14 -05:00
|
|
|
|
2023-07-28 19:50:04 +02:00
|
|
|
private async handleReservationErrors(
|
|
|
|
|
error: unknown,
|
|
|
|
|
reservation: Reservation,
|
|
|
|
|
) {
|
|
|
|
|
switch (true) {
|
|
|
|
|
case error instanceof NoCourtAvailableError: {
|
|
|
|
|
this.logger.warn('No court available, adding to waiting list')
|
|
|
|
|
await this.addReservationToWaitList(reservation)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
default:
|
|
|
|
|
this.logger.error('Error while performing reservation', { error })
|
|
|
|
|
throw error
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-27 16:06:19 +02:00
|
|
|
async performReservation(reservation: Reservation) {
|
2023-07-28 19:50:04 +02:00
|
|
|
try {
|
|
|
|
|
await this.brService.performReservation(reservation)
|
|
|
|
|
} catch (error: unknown) {
|
|
|
|
|
await this.handleReservationErrors(error, reservation)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async addReservationToWaitList(reservation: Reservation) {
|
|
|
|
|
await this.brService.addReservationToWaitList(reservation)
|
2023-06-27 16:06:19 +02:00
|
|
|
}
|
|
|
|
|
}
|