const DATA_DRAGON_BASE_URL = 'https://ddragon.leagueoflegends.com'; const CACHE_KEY = 'persona-lenz:data-dragon:champions:v1'; const CACHE_TTL_MS = 24 * 60 * 60 * 1000; export interface ChampionSummary { id: number; imageUrl: string; name: string; } export interface ChampionCatalog { champions: Record; version: string; } interface ChampionCatalogCache extends ChampionCatalog { cachedAt: number; } interface DataDragonChampion { image: { full: string; }; key: string; name: string; } interface DataDragonChampionResponse { data: Record; } export async function loadChampionCatalog(): Promise { const cachedCatalog = readChampionCatalogCache(); if (cachedCatalog && Date.now() - cachedCatalog.cachedAt < CACHE_TTL_MS) { return cachedCatalog; } try { const [latestVersion] = await fetchJson( `${DATA_DRAGON_BASE_URL}/api/versions.json`, ); if (!latestVersion) { throw new Error('Data Dragon 버전 목록이 비어 있습니다.'); } const championResponse = await fetchJson( `${DATA_DRAGON_BASE_URL}/cdn/${latestVersion}/data/ko_KR/champion.json`, ); const champions = Object.values(championResponse.data).reduce< Record >((catalog, champion) => { const championId = Number(champion.key); if (Number.isFinite(championId)) { catalog[championId] = { id: championId, imageUrl: `${DATA_DRAGON_BASE_URL}/cdn/${latestVersion}/img/champion/${champion.image.full}`, name: champion.name, }; } return catalog; }, {}); const catalog: ChampionCatalogCache = { cachedAt: Date.now(), champions, version: latestVersion, }; writeChampionCatalogCache(catalog); return catalog; } catch (error) { if (cachedCatalog) { return cachedCatalog; } throw error; } } function readChampionCatalogCache(): ChampionCatalogCache | null { let rawCache: string | null; try { rawCache = window.localStorage.getItem(CACHE_KEY); } catch { return null; } if (!rawCache) { return null; } try { const parsedCache = JSON.parse(rawCache) as Partial; if ( typeof parsedCache.cachedAt === 'number' && typeof parsedCache.version === 'string' && parsedCache.champions && typeof parsedCache.champions === 'object' ) { return parsedCache as ChampionCatalogCache; } } catch { removeChampionCatalogCache(); } return null; } function writeChampionCatalogCache(catalog: ChampionCatalogCache): void { try { window.localStorage.setItem(CACHE_KEY, JSON.stringify(catalog)); } catch { // Champion metadata remains usable even when browser storage is restricted. } } function removeChampionCatalogCache(): void { try { window.localStorage.removeItem(CACHE_KEY); } catch { // Ignore storage failures. } } async function fetchJson(url: string): Promise { const response = await fetch(url); if (!response.ok) { throw new Error(`Data Dragon 요청에 실패했습니다. (${response.status})`); } return (await response.json()) as T; }