summaryrefslogtreecommitdiff
path: root/src/misc/fetch-meta.ts
blob: 680cf37a727287ead1c9ded5ea27a6bd62ceb310 (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
import { Meta } from '../models/entities/meta';
import { getConnection } from 'typeorm';

let cache: Meta;

export async function fetchMeta(noCache = false): Promise<Meta> {
	if (!noCache && cache) return cache;

	return await getConnection().transaction(async transactionalEntityManager => {
		// 過去のバグでレコードが複数出来てしまっている可能性があるので新しいIDを優先する
		const meta = await transactionalEntityManager.findOne(Meta, {
			order: {
				id: 'DESC'
			}
		});

		if (meta) {
			cache = meta;
			return meta;
		} else {
			const saved = await transactionalEntityManager.save(Meta, {
				id: 'x'
			}) as Meta;

			cache = saved;
			return saved;
		}
	});
}

setInterval(() => {
	fetchMeta(true).then(meta => {
		cache = meta;
	});
}, 5000);