uptime-kuma/server/jobs/clear-old-data.js

53 lines
1.5 KiB
JavaScript
Raw Normal View History

const { R } = require("redbean-node");
2023-05-12 12:55:48 -04:00
const { log } = require("../../src/util");
const { setSetting, setting } = require("../util-server");
2021-10-12 11:28:21 -04:00
const DEFAULT_KEEP_PERIOD = 180;
2023-05-12 12:55:48 -04:00
/**
* Clears old data from the heartbeat table of the database.
* @return {Promise<void>} A promise that resolves when the data has been cleared.
*/
2023-05-12 12:55:48 -04:00
const clearOldData = async () => {
let period = await setting("keepDataPeriodDays");
// Set Default Period
if (period == null) {
2021-10-09 12:16:13 -04:00
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
period = DEFAULT_KEEP_PERIOD;
}
// Try parse setting
let parsedPeriod;
try {
parsedPeriod = parseInt(period);
} catch (_) {
2023-05-12 12:55:48 -04:00
log.warn("clearOldData", "Failed to parse setting, resetting to default..");
2021-10-09 12:16:13 -04:00
await setSetting("keepDataPeriodDays", DEFAULT_KEEP_PERIOD, "general");
parsedPeriod = DEFAULT_KEEP_PERIOD;
}
if (parsedPeriod < 1) {
2023-05-12 12:55:48 -04:00
log.info("clearOldData", `Data deletion has been disabled as period is less than 1. Period is ${parsedPeriod} days.`);
} else {
2023-05-12 12:55:48 -04:00
log.debug("clearOldData", `Clearing Data older than ${parsedPeriod} days...`);
try {
await R.exec(
"DELETE FROM heartbeat WHERE time < DATETIME('now', '-' || ? || ' days') ",
[ parsedPeriod ]
);
await R.exec("PRAGMA optimize;");
} catch (e) {
2023-05-12 12:55:48 -04:00
log.error("clearOldData", `Failed to clear old data: ${e.message}`);
}
}
2023-05-12 12:55:48 -04:00
};
2023-05-12 12:55:48 -04:00
module.exports = {
clearOldData,
};