DramaHarvester/src/db/services/DatabaseMaintenance.ts

69 lines
2.5 KiB
TypeScript

import { DatabaseService } from './Database';
/**
* Manages and executes database maintenance tasks such as purging old comments.
* This service is responsible for periodically running maintenance tasks based on specified intervals.
*/
export class DatabaseMaintenanceService {
/**
* A list of maintenance tasks to be executed, each with a name, action, and interval.
*/
private maintenanceTasks = [
{
name: 'PurgeOldComments',
action: this.purgeOldComments.bind(this),
interval: 24 * 60 * 60 * 1000, // 24 hours in milliseconds
},
// Add more tasks here as needed
];
/**
* Executes all maintenance tasks that are due based on their defined intervals.
*/
public async runMaintenanceTasks() {
for (const task of this.maintenanceTasks) {
const shouldRun = await this.shouldRunTask(task.name, task.interval);
if (shouldRun) {
await task.action();
await this.updateLastRunTimestamp(task.name);
}
}
}
/**
* Determines whether a specific maintenance task should run based on its last execution time and defined interval.
*
* @param {string} taskName - The name of the task to check.
* @param {number} interval - The interval in milliseconds to determine if the task should run.
* @returns {Promise<boolean>} True if the task should run, otherwise false.
*/
private async shouldRunTask(taskName: string, interval: number): Promise<boolean> {
// Use the DatabaseService to check the last run timestamp from the maintenance_log table
const lastRun = await DatabaseService.getLastRunTimestamp(taskName);
if (!lastRun) return true; // Task has never run
const now = Date.now();
return (now - lastRun.getTime()) > interval;
}
/**
* Purges old comments from the database.
*/
private async purgeOldComments() {
console.log("Purging old comments...");
// Use the DatabaseService for the SQL operation
await DatabaseService.purgeOldComments();
}
/**
* Updates the last run timestamp for a specific maintenance task.
*
* @param {string} taskName - The name of the task for which to update the last run timestamp.
*/
private async updateLastRunTimestamp(taskName: string) {
// Use the DatabaseService to update the last run timestamp in the maintenance_log table
await DatabaseService.updateLastRunTimestamp(taskName);
}
}