Skip to content

Commit 0141bdb

Browse files
authored
feat: persist star-helper user info in a json file (#160)
this should make it less annoying to deploy without losing cache state
1 parent 3d0421d commit 0141bdb

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

app/helpers/userInfoCache.ts

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { LRUCache } from "lru-cache";
22
import { rest } from "#~/discord/api.js";
33
import { Routes } from "discord.js";
4+
import fs from "node:fs/promises";
45

56
type DiscordUser = { username: string; global_name: string; id: string };
67

@@ -10,14 +11,30 @@ const cache = new LRUCache<string, DiscordUser>({
1011
max: 150,
1112
});
1213

14+
const cachefile = "./userInfoCache.json";
15+
load();
16+
1317
export async function getOrFetchUser(id: string) {
1418
if (cache.has(id)) return cache.get(id);
1519

16-
console.log("Fetching user from Discord API:", id);
17-
const { username, global_name } = (await rest.get(
18-
Routes.user(id),
19-
)) as DiscordUser;
20-
const result = { username, global_name, id };
20+
// @ts-expect-error FIXME: are there types available? schema validation?
21+
const { username, global_name } = await rest.get(Routes.user(id));
22+
const result = { id, username, global_name } as DiscordUser;
2123
cache.set(id, result);
24+
console.log("Fetched user from Discord API:", id);
25+
dump();
2226
return result;
2327
}
28+
29+
export function dump() {
30+
return fs.writeFile(cachefile, JSON.stringify(cache.dump()), "utf8");
31+
}
32+
33+
export async function load() {
34+
try {
35+
const raw = await fs.readFile(cachefile, "utf8");
36+
cache.load(JSON.parse(raw));
37+
} catch {
38+
// ignore errors, file might not exist yet
39+
}
40+
}

0 commit comments

Comments
 (0)