import config from "config"; import ApplicationComponent from "swaf/ApplicationComponent"; import MysqlComponent from "swaf/components/MysqlComponent"; import {WhereTest} from "swaf/db/ModelQuery"; import {logger} from "swaf/Logger"; import FileController from "./controllers/FileController.js"; import FileModel from "./models/FileModel.js"; import Timeout = NodeJS.Timeout; export default class DeleteOldFilesJobComponent extends ApplicationComponent { private timeout?: Timeout; private readonly interval: number = config.get('delete_old_files_interval'); public async start(): Promise { if (this.getApp().as(MysqlComponent).isReady()) { await this.run(); } this.schedule(); } public async stop(): Promise { if (this.timeout) { clearInterval(this.timeout); this.timeout = undefined; } } private schedule(): void { if (this.timeout) { clearInterval(this.timeout); this.timeout = undefined; } this.timeout = setInterval(() => { if (this.getApp().as(MysqlComponent).isReady()) { this.run().catch(err => logger.error(err)); } }, this.interval); logger.info(`Scheduled old file deletion job every ${this.interval}ms`); } private async run(): Promise { const filesToDelete = await FileModel.select() .where('expires_at', new Date(), WhereTest.LE) .get(); if (filesToDelete.length > 0) { logger.info('Deleting old files...'); } else { logger.info('No old file to delete.'); return; } for (const file of filesToDelete) { logger.info(`Deleting ${file.id}`); if (!file.shouldBeDeleted()) throw new Error('File should not be deleted.'); await FileController.deleteFile(file); } } }