99 lines
2.7 KiB
TypeScript
99 lines
2.7 KiB
TypeScript
import { getYoutubeSubscriberCount } from "./youtube";
|
|
import { getRobloxFollowerCount } from "./roblox";
|
|
import { getDiscordMemberCount } from "./discord";
|
|
import { getTiktokProfile, type TiktokProfile } from "./tiktok";
|
|
|
|
export type { TiktokProfile };
|
|
|
|
export interface FollowerCounts {
|
|
youtube: number | null;
|
|
roblox: number | null;
|
|
discord: number | null;
|
|
tiktok: number | null;
|
|
}
|
|
|
|
export interface FollowerInfo {
|
|
count: number;
|
|
label: string;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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 [youtube, roblox, discord, tiktokProfileResult] = await Promise.all([
|
|
getYoutubeSubscriberCount(),
|
|
getRobloxFollowerCount(),
|
|
getDiscordMemberCount(),
|
|
getTiktokProfile(),
|
|
]);
|
|
|
|
const counts: FollowerCounts = {
|
|
youtube,
|
|
roblox,
|
|
discord,
|
|
tiktok: tiktokProfileResult.followerCount,
|
|
};
|
|
|
|
try {
|
|
const { getRedisClient } = await import("@/lib/redis");
|
|
const redis = await getRedisClient();
|
|
await Promise.all([
|
|
redis.set(CACHE_KEY, JSON.stringify(counts), { ex: CACHE_TTL }),
|
|
redis.set(CACHE_KEY_TIKTOK, JSON.stringify(tiktokProfileResult), { ex: CACHE_TTL }),
|
|
]);
|
|
} catch {
|
|
// Redis unavailable, skip caching
|
|
}
|
|
|
|
return { counts, tiktokProfile: tiktokProfileResult };
|
|
}
|
|
|
|
const followerLabels: Record<keyof FollowerCounts, string> = {
|
|
youtube: "ผู้ติดตาม",
|
|
roblox: "เพื่อน",
|
|
discord: "สมาชิก",
|
|
tiktok: "ผู้ติดตาม",
|
|
};
|
|
|
|
export function getCountForLink(name: string, counts: FollowerCounts): FollowerInfo | null {
|
|
const key = name.toLowerCase();
|
|
for (const [platform, label] of Object.entries(followerLabels)) {
|
|
const count = counts[platform as keyof FollowerCounts];
|
|
if (key.includes(platform) && count !== null) {
|
|
return { count, label };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function formatCount(n: number): string {
|
|
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
|
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
|
|
return n.toString();
|
|
}
|
|
|