Untitled
unknown
plain_text
4 months ago
2.6 kB
9
Indexable
import { KeyValueCache, type Env } from "./key-value-cache"; import { SbsSettingsHelper, type UrlSettings } from "../shared/sbs-settings-helper"; import type { PageData } from "./types/PageData.types"; export class ContentAdapterService { public static async getHeaderData(urlSettings: UrlSettings, request: Request, env: Env) { const cacheKey = `${env.ENVIRONMENT}:header:${urlSettings.culture}`; const apiUrl = `${urlSettings.baseUrl}/api/content/${urlSettings.culture}/header/${urlSettings.partner}_header`; return await this.getCachedOrFetch(cacheKey, apiUrl, urlSettings, request, env); } public static async getFooterData(urlSettings: UrlSettings, request: Request, env: Env) { const cacheKey = `${env.ENVIRONMENT}:footer:${urlSettings.culture}`; const apiUrl = `${urlSettings.baseUrl}/api/content/${urlSettings.culture}/footer/${urlSettings.partner}_footer`; return await this.getCachedOrFetch(cacheKey, apiUrl, urlSettings, request, env); } public static async getPageData(urlSettings: UrlSettings, request: Request, slug: string, env: Env) { const formattedSlug = encodeURIComponent(slug); const cacheKey = `${env.ENVIRONMENT}:page:${urlSettings.culture}:${formattedSlug}`; const apiUrl = `${urlSettings.baseUrl}/api/content/${urlSettings.culture}/page/?slug=${formattedSlug}`; return await this.getCachedOrFetch<PageData>(cacheKey, apiUrl, urlSettings, request, env); } private static async getCachedOrFetch<T>( cacheKey: string, apiUrl: string, urlSettings: UrlSettings, request: Request, env: Env ): Promise<T> { const cachedData = await KeyValueCache.get(cacheKey, env); if (cachedData?.isValid) { console.log(`Loaded from cache: ${cacheKey}`); return cachedData.data as T; } const headers = SbsSettingsHelper.createAuthOnlyHeaders(urlSettings, request); const apiData = await this.fetchFromApi(apiUrl, headers); await KeyValueCache.put(cacheKey, apiData, true, env); console.log(`Stored in cache: ${cacheKey}`); return apiData as T; } private static async fetchFromApi(url: string, headers: Headers): Promise<any> { const response = await fetch(url, { headers }); if (!response.ok) { console.error(`API Fetch Failed: ${url} | Status: ${response.status}`); throw new Error(`API fetch failed for ${url}`); } return await response.json(); } }
Editor is loading...
Leave a Comment