aboutsummaryrefslogtreecommitdiff
path: root/src/tasks/updateCache.ts
blob: 3794f766766f988e29359df07474165e9c94e8d7 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Time } from '#constants';
import { Global, Guild, Shared, type BushClient } from '#lib';
import { BushTask } from '../lib/extensions/discord-akairo/BushTask.js';
import config from './../config/options.js';

export default class UpdateCacheTask extends BushTask {
	public constructor() {
		super('updateCache', {
			delay: 5 * Time.Minute,
			runOnStart: false // done in preinit task
		});
	}

	public override async exec() {
		await Promise.all([
			UpdateCacheTask.#updateGlobalCache(client),
			UpdateCacheTask.#updateSharedCache(client),
			UpdateCacheTask.#updateGuildCache(client)
		]);
		void client.logger.verbose(`UpdateCache`, `Updated cache.`);
	}

	public static async init(client: BushClient) {
		await Promise.all([
			UpdateCacheTask.#updateGlobalCache(client),
			UpdateCacheTask.#updateSharedCache(client),
			UpdateCacheTask.#updateGuildCache(client)
		]);
	}

	static async #updateGlobalCache(client: BushClient) {
		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];
			}
		}
	}

	static async #updateSharedCache(client: BushClient) {
		const row: { [x: string]: any } = ((await Shared.findByPk(0)) ?? (await Shared.create())).toJSON();

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

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