zappyzep/backend/src/data/cleanup/usernames.ts

40 lines
1 KiB
TypeScript
Raw Normal View History

import moment from "moment-timezone";
2023-07-01 12:17:45 +00:00
import { In } from "typeorm";
import { DAYS, DBDateFormat } from "../../utils";
2023-07-01 12:17:45 +00:00
import { dataSource } from "../dataSource";
import { UsernameHistoryEntry } from "../entities/UsernameHistoryEntry";
export const USERNAME_RETENTION_PERIOD = 30 * DAYS;
const CLEAN_PER_LOOP = 500;
export async function cleanupUsernames(): Promise<number> {
let cleaned = 0;
2023-07-01 12:17:45 +00:00
const usernameHistoryRepository = dataSource.getRepository(UsernameHistoryEntry);
2021-09-11 19:06:51 +03:00
const dateThreshold = moment.utc().subtract(USERNAME_RETENTION_PERIOD, "ms").format(DBDateFormat);
// Clean old usernames (USERNAME_RETENTION_PERIOD)
let rows;
do {
2023-07-01 12:17:45 +00:00
rows = await dataSource.query(
`
SELECT id
FROM username_history
WHERE timestamp < ?
LIMIT ${CLEAN_PER_LOOP}
`,
[dateThreshold],
);
if (rows.length > 0) {
await usernameHistoryRepository.delete({
2021-09-11 19:06:51 +03:00
id: In(rows.map((r) => r.id)),
});
}
cleaned += rows.length;
} while (rows.length === CLEAN_PER_LOOP);
return cleaned;
}