Files
lcbp3/backend/src/modules/notification/notification-cleanup.service.ts
T
admin 5dad7ab7c1
CI Pipeline / build (push) Failing after 9m47s
Build and Deploy / deploy (push) Failing after 4m42s
690322:2047 Fixing Deployment Blocking TypeScript Errors
2026-03-22 20:47:22 +07:00

44 lines
1.5 KiB
TypeScript

import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan } from 'typeorm';
import { Notification } from './entities/notification.entity';
@Injectable()
export class NotificationCleanupService {
private readonly logger = new Logger(NotificationCleanupService.name);
constructor(
@InjectRepository(Notification)
private notificationRepo: Repository<Notification>
) {}
/**
* ลบแจ้งเตือนที่ "อ่านแล้ว" และเก่ากว่า 30 วัน
* รันทุกวันเวลาเที่ยงคืน
*/
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
async handleCleanup() {
this.logger.log('Running notification cleanup...');
const daysAgo = 30;
const dateThreshold = new Date();
dateThreshold.setDate(dateThreshold.getDate() - daysAgo);
try {
const result = await this.notificationRepo
.createQueryBuilder()
.delete()
.from(Notification)
.where('is_read = :isRead', { isRead: true })
// Use column name 'created_at' explicitly
.andWhere('created_at < :dateThreshold', { dateThreshold })
.execute();
this.logger.log(`Deleted ${result.affected} old read notifications.`);
} catch (error) {
this.logger.error('Failed to cleanup notifications', error);
}
}
}