11import { LRUCache } from "lru-cache" ;
22import { rest } from "#~/discord/api.js" ;
33import { Routes } from "discord.js" ;
4+ import fs from "node:fs/promises" ;
45
56type 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+
1317export 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