52 lines
1.6 KiB
TypeScript
52 lines
1.6 KiB
TypeScript
import { getManager } from "typeorm";
|
|
import { DiscordCache } from "./DiscordCache";
|
|
import { DiscordToken } from "./DiscordToken";
|
|
import { StateToken } from "./StateToken";
|
|
|
|
/**
|
|
* pruneDB starts a long-running process that will prune the database every
|
|
* @interval seconds.
|
|
*
|
|
* This helps keep a low storage foot print for the different transient data
|
|
* structures this application has.
|
|
*
|
|
* @param {number} interval.
|
|
*
|
|
*/
|
|
export const pruneDB = (interval: number) => {
|
|
const manager = getManager();
|
|
|
|
// setInterval is a builtin JS function that will run the embedded function
|
|
// every interval.
|
|
setInterval(() => {
|
|
// Prune these tables. Determining when to prune is based on col, and the
|
|
// name of the table is in the name field.
|
|
const cleaning = [
|
|
{ type: StateToken, name: "state_tokens", col: "expiring" },
|
|
{ type: DiscordToken, name: "discord_tokens", col: "expiring" },
|
|
{ type: DiscordCache, name: "discord_cache", col: "expiring" },
|
|
];
|
|
|
|
// Run the query for each table in the cleaning array using a foreach.
|
|
//
|
|
// Sample SQL query generated:
|
|
// DELETE FROM [name]
|
|
// WHERE [name].[col] < datetime(:now)
|
|
//
|
|
// Will only remove columns that are past expiry date due to WHERE clause.
|
|
cleaning.forEach(({ type, name, col }) => {
|
|
manager
|
|
.createQueryBuilder()
|
|
.delete()
|
|
.from(type, name)
|
|
.where(`${name}.${col} < datetime(:now)`, {
|
|
now: new Date().toISOString(),
|
|
})
|
|
.execute()
|
|
.catch((err) => {
|
|
console.error("Error while pruning db: " + err);
|
|
});
|
|
});
|
|
}, interval);
|
|
};
|