mirror of
https://github.com/Dvorinka/MyClubServer.git
synced 2026-06-04 18:52:56 +00:00
dev day #79
This commit is contained in:
@@ -18,20 +18,37 @@ export type YouTubeChannelPayload = {
|
||||
videos: YouTubeVideo[];
|
||||
};
|
||||
|
||||
// Simple in-memory cache for YouTube payload (per-session)
|
||||
let ytMemCache: { payload: YouTubeChannelPayload | null; fetchedAt: number } | null = null;
|
||||
const YT_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
export const getCachedYouTube = async (): Promise<YouTubeChannelPayload | null> => {
|
||||
const now = Date.now();
|
||||
if (ytMemCache && now - ytMemCache.fetchedAt < YT_CACHE_TTL_MS) {
|
||||
return sortByPublishedDate(ytMemCache.payload) as YouTubeChannelPayload | null;
|
||||
}
|
||||
try {
|
||||
const res = await api.get('/youtube/videos');
|
||||
const primary = res?.data as YouTubeChannelPayload | undefined;
|
||||
const hasVideos = Array.isArray(primary?.videos) && (primary!.videos.length > 0);
|
||||
// If backend responded with 204 or empty payload, fall back to the static cached JSON
|
||||
let out: YouTubeChannelPayload | null = null;
|
||||
if (res.status === 204 || !primary || !hasVideos) {
|
||||
const fallback = await fetchStaticYouTubeCache();
|
||||
return sortByPublishedDate(fallback);
|
||||
out = await fetchStaticYouTubeCache();
|
||||
} else {
|
||||
out = primary || null;
|
||||
}
|
||||
return sortByPublishedDate(primary) as YouTubeChannelPayload;
|
||||
if (out) {
|
||||
ytMemCache = { payload: out, fetchedAt: now };
|
||||
}
|
||||
return sortByPublishedDate(out) as YouTubeChannelPayload | null;
|
||||
} catch {
|
||||
// Fallback: fetch static cached JSON directly from backend /cache path to avoid stressing external API
|
||||
return await fetchStaticYouTubeCache();
|
||||
const out = await fetchStaticYouTubeCache();
|
||||
if (out) {
|
||||
ytMemCache = { payload: out, fetchedAt: now };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -40,7 +57,7 @@ const fetchStaticYouTubeCache = async (): Promise<YouTubeChannelPayload | null>
|
||||
try {
|
||||
const origin = new URL(API_URL, typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000').origin;
|
||||
const url = `${origin}/cache/prefetch/youtube_channel.json`;
|
||||
const resp = await fetch(url, { cache: 'no-cache' });
|
||||
const resp = await fetch(url, { cache: 'force-cache' });
|
||||
if (!resp.ok) return null;
|
||||
const data = (await resp.json()) as YouTubeChannelPayload;
|
||||
return sortByPublishedDate(data);
|
||||
|
||||
Reference in New Issue
Block a user