add crone to remove notifs

This commit is contained in:
2025-12-20 20:29:17 +03:30
parent fae38c427d
commit e0df01053b
2 changed files with 48 additions and 0 deletions
@@ -0,0 +1,46 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { EntityManager } from '@mikro-orm/postgresql';
import { Notification } from '../entities/notification.entity';
@Injectable()
export class NotificationCrone {
private readonly logger = new Logger(NotificationCrone.name);
constructor(private readonly em: EntityManager) {}
// run every day at 03:00 (3:00 AM)
@Cron('0 3 * * *', {
name: 'deleteOldNotifications',
timeZone: 'UTC',
})
async handleCron() {
try {
this.logger.debug('Starting daily notification cleanup (removing notifications older than 24 hours)');
// Calculate the date 24 hours ago
const twentyFourHoursAgo = new Date();
twentyFourHoursAgo.setHours(twentyFourHoursAgo.getHours() - 24);
// Find all notifications created more than 24 hours ago
const oldNotifications = await this.em.find(Notification, {
createdAt: { $lt: twentyFourHoursAgo },
});
if (!oldNotifications || oldNotifications.length === 0) {
this.logger.debug('No old notifications found to delete');
return;
}
this.logger.log(`Found ${oldNotifications.length} notifications older than 24 hours to delete`);
// Delete the old notifications
await this.em.removeAndFlush(oldNotifications);
this.logger.log(`Successfully deleted ${oldNotifications.length} old notifications`);
} catch (err) {
this.logger.error(`NotificationCrone failed: ${err?.message}`, err);
}
}
}
@@ -22,6 +22,7 @@ import { WsAdminAuthGuard } from './guards/ws-admin-auth.guard';
import { InAppProcessor } from './processors/in-app.processor';
import { AdminModule } from '../admin/admin.module';
import { UserModule } from '../users/user.module';
import { NotificationCrone } from './crone/notification.crone';
@Module({
imports: [
@@ -58,6 +59,7 @@ import { UserModule } from '../users/user.module';
InAppProcessor,
NotificationsGateway,
WsAdminAuthGuard,
NotificationCrone,
],
exports: [NotificationService, NotificationPreferenceService, NotificationQueueService, PushNotificationService],
})