-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguildConfig.ts
90 lines (80 loc) · 2.22 KB
/
guildConfig.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import loadJsonFile from "load-json-file";
import makeDir from "make-dir";
import { resolve } from "path";
import { readdir } from "fs/promises";
import writeJsonFile from "write-json-file";
const defaultConfigDir = "configs";
const configDir = resolve(
__dirname,
process.env.CONFIG_DIR || defaultConfigDir
);
export interface SwapCriteria {
upperThreshold: number | null;
lowerThreshold: number | null;
}
export interface GuildConfig {
guildId: string;
guildName: string;
configVersion: number;
channelConfigs: {
[channelId: string]: {
swapTitle: string;
swapCriteria: SwapCriteria;
};
};
}
export const defaultSwapTitle = "🚨🐳 Big Swap Alert! 🐳🚨";
export const defaultGuildConfig: GuildConfig = {
guildId: "",
guildName: "",
configVersion: 1,
channelConfigs: {},
};
const cachedGuildConfigs: {
[guildId: string]: GuildConfig;
} = {};
export const makeConfigDir = async () => {
const dir = await makeDir(configDir);
return `Config dir: ${dir}`;
};
export const loadAllConfigs = async () => {
const configFiles = (await readdir(configDir)).filter((file) =>
file.endsWith(".json")
);
const loadFilePromises = configFiles.map((configFile) =>
loadJsonFile<GuildConfig>(resolve(configDir, configFile))
);
const configs = await Promise.all(loadFilePromises);
configs.forEach((config) => {
cachedGuildConfigs[config.guildId] = config;
});
console.log(`Successfully loaded ${loadFilePromises.length} configs`);
return cachedGuildConfigs;
};
export const getGuildConfig = async (guildId: string, guildName: string) => {
if (cachedGuildConfigs[guildId]) return cachedGuildConfigs[guildId];
try {
return await loadJsonFile<GuildConfig>(
resolve(configDir, `${guildId}.json`)
);
} catch (e) {
const newConfig = {
...defaultGuildConfig,
guildName,
guildId,
};
await saveGuildConfig(newConfig, guildId);
return newConfig;
}
};
export const saveGuildConfig = async (
config: GuildConfig,
guildId?: string
) => {
let resolvedId = guildId;
if (!resolvedId) {
resolvedId = config.guildId;
}
cachedGuildConfigs[resolvedId] = config;
return await writeJsonFile(resolve(configDir, `${resolvedId}.json`), config);
};