2020-06-02 00:26:06 +03:00
|
|
|
import moment from "moment-timezone";
|
2023-07-01 12:17:45 +00:00
|
|
|
import { In } from "typeorm";
|
2020-08-19 00:19:12 +03:00
|
|
|
import { DAYS, DBDateFormat } from "../../utils";
|
2023-07-01 12:17:45 +00:00
|
|
|
import { dataSource } from "../dataSource";
|
2021-06-06 23:51:32 +02:00
|
|
|
import { UsernameHistoryEntry } from "../entities/UsernameHistoryEntry";
|
2020-06-02 00:26:06 +03:00
|
|
|
|
|
|
|
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);
|
2020-06-02 00:26:06 +03:00
|
|
|
|
|
|
|
// Clean old usernames (USERNAME_RETENTION_PERIOD)
|
|
|
|
let rows;
|
|
|
|
do {
|
2023-07-01 12:17:45 +00:00
|
|
|
rows = await dataSource.query(
|
2020-06-02 00:26:06 +03:00
|
|
|
`
|
|
|
|
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)),
|
2020-06-02 00:26:06 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
cleaned += rows.length;
|
|
|
|
} while (rows.length === CLEAN_PER_LOOP);
|
|
|
|
|
|
|
|
return cleaned;
|
|
|
|
}
|