this repo has no description
1import { getCachetUser } from "./cachet";
2
3interface CachedUserInfo {
4 name: string;
5 realName: string;
6 timestamp: number;
7}
8
9interface SlackClient {
10 users: {
11 info: (params: { token: string; user: string }) => Promise<{
12 user?: {
13 name?: string;
14 real_name?: string;
15 };
16 }>;
17 };
18}
19
20const userCache = new Map<string, CachedUserInfo>();
21const CACHE_TTL = 60 * 60 * 1000; // 1 hour
22
23/**
24 * Get user info from cache or fetch from Cachet (if enabled) or Slack API
25 * If displayName is provided (from Slack event), use that directly and cache it
26 */
27export async function getUserInfo(
28 userId: string,
29 slackClient: SlackClient,
30 displayName?: string,
31): Promise<{ name: string; realName: string } | null> {
32 const cached = userCache.get(userId);
33 const now = Date.now();
34
35 if (cached && now - cached.timestamp < CACHE_TTL) {
36 return { name: cached.name, realName: cached.realName };
37 }
38
39 // If we have a display name from the event, use it directly
40 if (displayName) {
41 userCache.set(userId, {
42 name: displayName,
43 realName: displayName,
44 timestamp: now,
45 });
46
47 return { name: displayName, realName: displayName };
48 }
49
50 // Try Cachet first if enabled (it has its own caching)
51 if (process.env.CACHET_ENABLED === "true") {
52 try {
53 const cachetUser = await getCachetUser(userId);
54 if (cachetUser) {
55 const name = cachetUser.displayName || "Unknown";
56 const realName = cachetUser.displayName || "Unknown";
57
58 userCache.set(userId, {
59 name,
60 realName,
61 timestamp: now,
62 });
63
64 return { name, realName };
65 }
66 } catch (error) {
67 console.error(`Error fetching user from Cachet for ${userId}:`, error);
68 }
69 }
70
71 // Fallback to Slack API
72 try {
73 const userInfo = await slackClient.users.info({
74 token: process.env.SLACK_BOT_TOKEN,
75 user: userId,
76 });
77
78 const name = userInfo.user?.name || "Unknown";
79 const realName = userInfo.user?.real_name || name;
80
81 userCache.set(userId, {
82 name,
83 realName,
84 timestamp: now,
85 });
86
87 return { name, realName };
88 } catch (error) {
89 console.error(`Error fetching user info for ${userId}:`, error);
90 return null;
91 }
92}
93
94/**
95 * Clear expired entries from cache
96 */
97export function cleanupUserCache(): void {
98 const now = Date.now();
99 for (const [userId, info] of userCache.entries()) {
100 if (now - info.timestamp > CACHE_TTL) {
101 userCache.delete(userId);
102 }
103 }
104}