implemented server cache for content array

This commit is contained in:
2026-11-05 13:42:51 +00:00
parent 834fb754ae
commit 08c174ba82

View File

@@ -16,6 +16,20 @@ export interface ContentItem {
type: ContentType; type: ContentType;
} }
const CACHE_TTL = 3 * 60 * 60 * 1000;
interface CacheEntry<T> {
value: T;
expiresAt: number;
}
const contentCache = new Map<string, CacheEntry<ContentItem[]>>();
const pendingRequests = new Map<string, Promise<ContentItem[]>>();
function getCacheKey(channelId: string, blogUrl: string): string {
return JSON.stringify([channelId, blogUrl]);
}
const parser = new XMLParser({ const parser = new XMLParser({
ignoreAttributes: false, ignoreAttributes: false,
attributeNamePrefix: '@_', attributeNamePrefix: '@_',
@@ -100,7 +114,7 @@ async function getLatestContent(
return items; return items;
} }
export async function getContentItems( async function fetchContentItems(
fetch: typeof globalThis.fetch, fetch: typeof globalThis.fetch,
channelId: string, channelId: string,
blogUrl: string blogUrl: string
@@ -114,3 +128,42 @@ export async function getContentItems(
return finalArray.slice(0, 5); return finalArray.slice(0, 5);
} }
export async function getContentItems(
fetch: typeof globalThis.fetch,
channelId: string,
blogUrl: string
): Promise<ContentItem[]> {
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));
}