Files
erika/lib/followers/index.ts
T

75 lines
2.1 KiB
TypeScript

import { unstable_cache } from "next/cache";
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;
}
const getFollowerCountsFromAPIs = unstable_cache(
async (): 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 };
},
['follower-counts-api'],
{ revalidate: 3600, tags: ['follower-counts-api'] }
);
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 getFollowerCountsFromAPIs();
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;
}