summaryrefslogtreecommitdiff
path: root/packages/backend/src/services/register-or-fetch-instance-doc.ts
blob: a548ab04972d09b1b7e7efa2856979d7c0e1439c (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
import { Instance } from '@/models/entities/instance';
import { Instances } from '@/models/index';
import { federationChart } from '@/services/chart/index';
import { genId } from '@/misc/gen-id';
import { toPuny } from '@/misc/convert-host';
import { Cache } from '@/misc/cache';

const cache = new Cache<Instance>(1000 * 60 * 60);

export async function registerOrFetchInstanceDoc(host: string): Promise<Instance> {
	host = toPuny(host);

	const cached = cache.get(host);
	if (cached) return cached;

	const index = await Instances.findOne({ host });

	if (index == null) {
		const i = await Instances.save({
			id: genId(),
			host,
			caughtAt: new Date(),
			lastCommunicatedAt: new Date(),
		});

		federationChart.update(true);

		cache.set(host, i);
		return i;
	} else {
		cache.set(host, index);
		return index;
	}
}