|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { Cron, CronExpression } from '@nestjs/schedule'; |
| 3 | +import { PrismaService } from '../prisma/prisma.service'; |
| 4 | +import { addHours } from '@/utils'; |
| 5 | +import { priorityExpiryInterval } from './constants'; |
| 6 | +import { SupplyPriority } from '../supply/types'; |
| 7 | +import { ShelterSupplyService } from './shelter-supply.service'; |
| 8 | + |
| 9 | +@Injectable() |
| 10 | +export class ShelterSupplyExpirationJob { |
| 11 | + constructor( |
| 12 | + private readonly prismaService: PrismaService, |
| 13 | + private readonly shelterSupplyService: ShelterSupplyService, |
| 14 | + ) {} |
| 15 | + |
| 16 | + private readonly logger = new Logger(ShelterSupplyExpirationJob.name); |
| 17 | + |
| 18 | + @Cron(CronExpression.EVERY_10_SECONDS) |
| 19 | + async handleCron() { |
| 20 | + this.logger.log(`${ShelterSupplyExpirationJob.name} running`); |
| 21 | + |
| 22 | + const expiryDate = addHours(new Date(Date.now()), -priorityExpiryInterval); |
| 23 | + const supplies = await this.prismaService.shelterSupply.findMany({ |
| 24 | + select: { |
| 25 | + supplyId: true, |
| 26 | + shelterId: true, |
| 27 | + createdAt: true, |
| 28 | + }, |
| 29 | + where: { |
| 30 | + priority: SupplyPriority.Urgent, |
| 31 | + }, |
| 32 | + }); |
| 33 | + |
| 34 | + supplies.forEach(async (s) => { |
| 35 | + const { shelterId, supplyId, createdAt } = s; |
| 36 | + if (new Date(createdAt) <= expiryDate) { |
| 37 | + await this.shelterSupplyService.update({ |
| 38 | + data: { |
| 39 | + priority: SupplyPriority.Needing, |
| 40 | + }, |
| 41 | + where: { shelterId: shelterId, supplyId: supplyId }, |
| 42 | + }); |
| 43 | + } |
| 44 | + }); |
| 45 | + } |
| 46 | +} |
0 commit comments