const cron = require("node-cron"); const { Op } = require("sequelize"); const { sequelize, notification, userNotification } = require("../app/models"); module.exports = function startCleanInactiveNotificationsCron() { const task = cron.schedule("0 0 * * *", async () => { const cutoff = new Date(Date.now() - Number(process.env.NOTIFICATION_RETENTION_DAYS || 90) * 86400000); for (;;) { const rows = await notification.findAll({ where: { isActive: false, updatedAt: { [Op.lt]: cutoff } }, attributes: ["notification_id"], limit: 500, order: [["updatedAt", "ASC"]] }); if (!rows.length) break; const ids = rows.map((row) => row.notification_id); await sequelize.transaction(async (transaction) => { await userNotification.destroy({ where: { notification_id: { [Op.in]: ids } }, transaction }); await notification.destroy({ where: { notification_id: { [Op.in]: ids }, isActive: false }, transaction }); }); if (rows.length < 500) break; } }, { scheduled: false }); task.start(); return task; };