Files
erika/lib/followers/index.ts
T

75 lines
1.9 KiB
TypeScript

import { getYoutubeSubscriberCount } from "./youtube";
import { getRobloxFollowerCount } from "./roblox";
import { getDiscordMemberCount } from "./discord";
import { getTiktokProfile, type TiktokProfile } from "./tiktok";
export type { TiktokProfile };
import { FollowerCounts } from "./utils";
const CACHE_KEY = "erika:follower_counts";
const CACHE_KEY_TIKTOK = "erika:tiktok_profile";
const CACHE_TTL = 3600; // 1 hour
export interface FetchResult {
counts: FollowerCounts;
tiktokProfile: TiktokProfile;
}
async function fetchFollowerCountsFromAPIs(): Promise<FetchResult> {
const [youtube, roblox, discord, tiktokProfileResult] = await Promise.all([
getYoutubeSubscriberCount(),
getRobloxFollowerCount(),
getDiscordMemberCount(),
getTiktokProfile(),
]);
const counts: FollowerCounts = {
youtube,
roblox,
discord,
tiktok: tiktokProfileResult.followerCount,
};
return { counts, tiktokProfile: tiktokProfileResult };
}
export async function getFollowerCounts(): Promise<FetchResult> {
try {
const { getRedisClient } = await import("@/lib/redis");
const redis = await getRedisClient();
const [cachedCounts, cachedProfile] = await Promise.all([
redis.get(CACHE_KEY),
redis.get(CACHE_KEY_TIKTOK),
]);
if (cachedCounts && cachedProfile) {
return {
counts: JSON.parse(cachedCounts),
tiktokProfile: JSON.parse(cachedProfile),
};
}
} catch {
// Redis unavailable, fall through to fetch
}
const result = await fetchFollowerCountsFromAPIs();
try {
const { getRedisClient } = await import("@/lib/redis");
const redis = await getRedisClient();
await Promise.all([
redis.set(CACHE_KEY, JSON.stringify(result.counts), "EX", CACHE_TTL),
redis.set(
CACHE_KEY_TIKTOK,
JSON.stringify(result.tiktokProfile),
"EX",
CACHE_TTL,
),
]);
} catch {
// Redis unavailable, skip caching
}
return result;
}