summaryrefslogtreecommitdiff
path: root/packages/backend/src/daemons/JanitorService.ts
blob: 8cdfb703f1c3f15d1fb42cbf4e6ab19fa28c3b8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { Inject, Injectable } from '@nestjs/common';
import { LessThan } from 'typeorm';
import { DI } from '@/di-symbols.js';
import type { AttestationChallengesRepository } from '@/models/index.js';
import { bindThis } from '@/decorators.js';
import type { OnApplicationShutdown } from '@nestjs/common';

const interval = 30 * 60 * 1000;

@Injectable()
export class JanitorService implements OnApplicationShutdown {
	private intervalId: NodeJS.Timer;

	constructor(
		@Inject(DI.attestationChallengesRepository)
		private attestationChallengesRepository: AttestationChallengesRepository,
	) {
	}

	/**
	 * Clean up database occasionally
	 */
	@bindThis
	public start(): void {
		const tick = async () => {
			await this.attestationChallengesRepository.delete({
				createdAt: LessThan(new Date(new Date().getTime() - 5 * 60 * 1000)),
			});
		};

		tick();

		this.intervalId = setInterval(tick, interval);
	}

	@bindThis
	public onApplicationShutdown(signal?: string | undefined) {
		clearInterval(this.intervalId);
	}
}