import { Injectable, Logger } from '@nestjs/common'; import { RedisService } from '../global/redis/redis.service'; const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com'; const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`; const DEFAULT_LOCALE = 'ko_KR'; const CACHE_TTL_SECONDS = 24 * 60 * 60; const CACHE_VERSION = 'v5'; const FETCH_TIMEOUT_MS = 10_000; export interface DdragonChampionEntry { key: string; name: string; } export interface DdragonSummonerSpellEntry { key: string; name: string; description: string; tooltip: string; } export interface DdragonRuneEntry { id: number; key: string; icon: string; name: string; shortDesc: string; longDesc: string; } export interface DdragonRuneStyleEntry extends DdragonRuneEntry { slots: Array<{ runes: DdragonRuneEntry[] }>; } export interface DdragonItemEntry { name: string; description: string; plaintext: string; gold: { base: number; total: number; sell: number; purchasable: boolean; }; } export interface DdragonManifest { version: string; cdn: string; locale: string; champions: Record; summonerSpells: Record; runesReforged: DdragonRuneStyleEntry[]; items: Record; fetchedAt: string; } interface ChampionDataEntry { key: string; id: string; name: string; } interface ChampionDataResponse { data: Record; } interface SummonerSpellDataEntry { key: string; id: string; name: string; description?: string; tooltip?: string; } interface SummonerSpellDataResponse { data: Record; } interface RuneDataEntry { id: number; key: string; icon: string; name: string; shortDesc?: string; longDesc?: string; } interface RuneStyleDataEntry extends RuneDataEntry { slots?: Array<{ runes?: RuneDataEntry[] }>; } interface ItemDataEntry { name?: string; description?: string; plaintext?: string; gold?: { base?: number; total?: number; sell?: number; purchasable?: boolean; }; } interface ItemDataResponse { data: Record; } @Injectable() export class RiotDdragonService { private readonly logger = new Logger(RiotDdragonService.name); private inflight = new Map>(); constructor(private readonly redisService: RedisService) {} public async getManifest( locale: string = DEFAULT_LOCALE, ): Promise { const normalizedLocale = normalizeLocale(locale); const cacheKey = manifestCacheKey(normalizedLocale); const cached = await this.redisService.getJson(cacheKey); if (cached) return cached; const pending = this.inflight.get(cacheKey); if (pending) return pending; const promise = this.buildManifest(normalizedLocale) .then(async (manifest) => { await this.redisService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS); return manifest; }) .finally(() => { this.inflight.delete(cacheKey); }); this.inflight.set(cacheKey, promise); return promise; } private async buildManifest(locale: string): Promise { const version = await this.fetchLatestVersion(); const [champions, summonerSpells, runesReforged, items] = await Promise.all( [ this.fetchChampionMap(version, locale), this.fetchSummonerSpellMap(version, locale), this.fetchRuneStyles(version, locale), this.fetchItemMap(version, locale), ], ); return { version, cdn: DDRAGON_CDN, locale, champions, summonerSpells, runesReforged, items, fetchedAt: new Date().toISOString(), }; } private async fetchLatestVersion(): Promise { const versions = await this.fetchJson( `${DDRAGON_BASE}/api/versions.json`, ); if (!Array.isArray(versions) || typeof versions[0] !== 'string') { throw new Error('ddragon versions.json response is malformed.'); } return versions[0]; } private async fetchChampionMap( version: string, locale: string, ): Promise> { const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`; const payload = await this.fetchJson(url); if (!payload || typeof payload !== 'object' || !payload.data) { throw new Error(`ddragon champion.json response is malformed (${url}).`); } const map: Record = {}; for (const entry of Object.values(payload.data)) { if (entry?.key && entry.id) { map[entry.key] = { key: entry.id, name: typeof entry.name === 'string' ? entry.name : entry.id, }; } } return map; } private async fetchSummonerSpellMap( version: string, locale: string, ): Promise> { const url = `${DDRAGON_CDN}/${version}/data/${locale}/summoner.json`; const payload = await this.fetchJson(url); if (!payload || typeof payload !== 'object' || !payload.data) { throw new Error(`ddragon summoner.json response is malformed (${url}).`); } const map: Record = {}; for (const entry of Object.values(payload.data)) { if (entry?.key && entry.id) { map[entry.key] = { key: entry.id, name: typeof entry.name === 'string' ? entry.name : entry.id, description: typeof entry.description === 'string' ? entry.description : '', tooltip: typeof entry.tooltip === 'string' ? entry.tooltip : '', }; } } return map; } private async fetchRuneStyles( version: string, locale: string, ): Promise { const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`; const payload = await this.fetchJson(url); if (!Array.isArray(payload)) { throw new Error( `ddragon runesReforged.json response is malformed (${url}).`, ); } return payload .filter((style): style is RuneStyleDataEntry => isRuneEntry(style)) .map((style) => ({ id: style.id, key: style.key, icon: style.icon, name: style.name, shortDesc: typeof style.shortDesc === 'string' ? style.shortDesc : '', longDesc: typeof style.longDesc === 'string' ? style.longDesc : '', slots: (style.slots ?? []).map((slot) => ({ runes: (slot.runes ?? []) .filter((rune): rune is RuneDataEntry => isRuneEntry(rune)) .map((rune) => ({ id: rune.id, key: rune.key, icon: rune.icon, name: rune.name, shortDesc: typeof rune.shortDesc === 'string' ? rune.shortDesc : '', longDesc: typeof rune.longDesc === 'string' ? rune.longDesc : '', })), })), })); } private async fetchItemMap( version: string, locale: string, ): Promise> { const url = `${DDRAGON_CDN}/${version}/data/${locale}/item.json`; const payload = await this.fetchJson(url); if (!payload || typeof payload !== 'object' || !payload.data) { throw new Error(`ddragon item.json response is malformed (${url}).`); } const map: Record = {}; for (const [itemId, entry] of Object.entries(payload.data)) { if (!/^\d+$/.test(itemId) || typeof entry?.name !== 'string') { continue; } map[itemId] = { name: entry.name, description: typeof entry.description === 'string' ? entry.description : '', plaintext: typeof entry.plaintext === 'string' ? entry.plaintext : '', gold: { base: numberOrZero(entry.gold?.base), total: numberOrZero(entry.gold?.total), sell: numberOrZero(entry.gold?.sell), purchasable: entry.gold?.purchasable ?? false, }, }; } return map; } private async fetchJson(url: string): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); try { const response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json' }, signal: controller.signal, }); if (!response.ok) { throw new Error(`ddragon request failed (${response.status}): ${url}`); } return (await response.json()) as T; } catch (err) { this.logger.error( `ddragon fetch error for ${url}: ${(err as Error)?.message ?? err}`, ); throw err; } finally { clearTimeout(timeout); } } } function normalizeLocale(locale: string): string { const trimmed = locale.trim(); if (!/^[a-zA-Z]{2}_[a-zA-Z]{2}$/.test(trimmed)) { return DEFAULT_LOCALE; } return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`; } function isRuneEntry(value: unknown): value is RuneDataEntry { if (!value || typeof value !== 'object') return false; const entry = value as Partial; return ( typeof entry.id === 'number' && typeof entry.key === 'string' && typeof entry.icon === 'string' && typeof entry.name === 'string' ); } function numberOrZero(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) ? value : 0; } function manifestCacheKey(locale: string): string { return `ddragon:manifest:${CACHE_VERSION}:${locale}`; }