From 08c174ba82cf346f5c93786a60b333716690e426 Mon Sep 17 00:00:00 2001 From: voidarc Date: Thu, 5 Nov 2026 13:42:51 +0000 Subject: [PATCH] implemented server cache for content array --- src/lib/server/content.ts | 55 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/src/lib/server/content.ts b/src/lib/server/content.ts index 7456e38..0f85e44 100644 --- a/src/lib/server/content.ts +++ b/src/lib/server/content.ts @@ -16,6 +16,20 @@ export interface ContentItem { type: ContentType; } +const CACHE_TTL = 3 * 60 * 60 * 1000; + +interface CacheEntry { + value: T; + expiresAt: number; +} + +const contentCache = new Map>(); +const pendingRequests = new Map>(); + +function getCacheKey(channelId: string, blogUrl: string): string { + return JSON.stringify([channelId, blogUrl]); +} + const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', @@ -100,7 +114,7 @@ async function getLatestContent( return items; } -export async function getContentItems( +async function fetchContentItems( fetch: typeof globalThis.fetch, channelId: string, blogUrl: string @@ -114,3 +128,42 @@ export async function getContentItems( return finalArray.slice(0, 5); } + +export async function getContentItems( + fetch: typeof globalThis.fetch, + channelId: string, + blogUrl: string +): Promise { + const cacheKey = getCacheKey(channelId, blogUrl); + + const cached = contentCache.get(cacheKey); + + if (cached && cached.expiresAt > Date.now()) { + return cached.value; + } + + const pending = pendingRequests.get(cacheKey); + + if (pending) return pending; + + const request = fetchContentItems(fetch, channelId, blogUrl) + .then((items) => { + contentCache.set(cacheKey, { + value: items, + expiresAt: Date.now() + CACHE_TTL + }); + + return items; + }) + .finally(() => { + pendingRequests.delete(cacheKey); + }); + + pendingRequests.set(cacheKey, request); + + return request; +} + +export function invalidateContentCache(channelId: string, blogUrl: string): void { + contentCache.delete(getCacheKey(channelId, blogUrl)); +}