a fun bot for the hc slack
at main 1.6 kB view raw
1export async function fetchUserData(userId: string) { 2 const res = await fetch(`https://cachet.dunkirk.sh/users/${userId}/`); 3 const json = await res.json(); 4 5 return { 6 id: json.id, 7 expiration: json.expiration, 8 user: json.user, 9 displayName: json.displayName, 10 image: json.image, 11 }; 12} 13 14export const userService = { 15 cache: {} as Record<string, { name: string; timestamp: number }>, 16 pendingRequests: {} as Record<string, Promise<string>>, 17 CACHE_TTL: 5 * 60 * 1000, 18 19 async getUserName(userId: string): Promise<string> { 20 const now = Date.now(); 21 22 // Check if user data is in cache and still valid 23 if ( 24 this.cache[userId] && 25 now - this.cache[userId].timestamp < this.CACHE_TTL 26 ) { 27 return this.cache[userId].name; 28 } 29 30 // If there's already a pending request for this user, return that promise 31 // instead of creating a new request 32 if (this.pendingRequests[userId]) { 33 return this.pendingRequests[userId]; 34 } 35 36 // Create a new promise for this user and store it 37 const fetchPromise = (async () => { 38 try { 39 const userData = await fetchUserData(userId); 40 const userName = userData?.displayName || "Unknown User"; 41 42 this.cache[userId] = { 43 name: userName, 44 timestamp: now, 45 }; 46 47 return userName; 48 } catch (error) { 49 console.error("Error fetching user data:", error); 50 return "Unknown User"; 51 } finally { 52 // Clean up the pending request when done 53 delete this.pendingRequests[userId]; 54 } 55 })(); 56 57 // Store the promise 58 this.pendingRequests[userId] = fetchPromise; 59 60 // Return the promise 61 return fetchPromise; 62 }, 63};