aboutsummaryrefslogtreecommitdiff
path: root/src/tasks/updateCache.ts
blob: e9d0cc6f38ed518f80dd2955a677d845541aa57e (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
41
42
43
import { BushClient } from '../lib/extensions/discord-akairo/BushClient';
import { BushTask } from '../lib/extensions/discord-akairo/BushTask';
import { Global } from '../lib/models/Global';
import { Guild } from '../lib/models/Guild';
import config from './../config/options';

export default class UpdateCacheTask extends BushTask {
	public constructor() {
		super('updateCache', {
			delay: 300_000, // 5 minutes
			runOnStart: false // done in preinit task
		});
	}
	public override async exec(): Promise<void> {
		await UpdateCacheTask.updateGlobalCache(client);
		await UpdateCacheTask.#updateGuildCache(client);
		void client.logger.verbose(`UpdateCache`, `Updated cache.`);
	}

	public static async init(client: BushClient): Promise<void> {
		await UpdateCacheTask.updateGlobalCache(client);
		await UpdateCacheTask.#updateGuildCache(client);
	}

	private static async updateGlobalCache(client: BushClient): Promise<void> {
		const environment = config.environment;
		const row: { [x: string]: any } = ((await Global.findByPk(environment)) ?? (await Global.create({ environment }))).toJSON();

		for (const option in row) {
			if (Object.keys(client.cache.global).includes(option)) {
				client.cache.global[option as keyof typeof client.cache.global] = row[option];
				if (option === 'superUsers') client.superUserID = row[option];
			}
		}
	}

	static async #updateGuildCache(client: BushClient): Promise<void> {
		const rows = await Guild.findAll();
		for (const row of rows) {
			client.cache.guilds.set(row.id, row.toJSON() as Guild);
		}
	}
}