feat(api): add Riot match and ddragon services
This commit is contained in:
1 parent
5361dc8adb
commit
463c839782
4 files changed
+1008
No files matched your search
@@ -0,0 +1,250 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { GarnetService } from '../global/garnet/garnet.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 = 'v3';
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
export interface DdragonChampionEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonSummonerSpellEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneEntry {
|
||||
id: number;
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
||||
slots: Array<{ runes: DdragonRuneEntry[] }>;
|
||||
}
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
locale: string;
|
||||
champions: Record<string, DdragonChampionEntry>;
|
||||
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
||||
runesReforged: DdragonRuneStyleEntry[];
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
interface ChampionDataEntry {
|
||||
key: string;
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface ChampionDataResponse {
|
||||
data: Record<string, ChampionDataEntry>;
|
||||
}
|
||||
|
||||
interface SummonerSpellDataEntry {
|
||||
key: string;
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface SummonerSpellDataResponse {
|
||||
data: Record<string, SummonerSpellDataEntry>;
|
||||
}
|
||||
|
||||
interface RuneDataEntry {
|
||||
id: number;
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface RuneStyleDataEntry extends RuneDataEntry {
|
||||
slots?: Array<{ runes?: RuneDataEntry[] }>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotDdragonService {
|
||||
private readonly logger = new Logger(RiotDdragonService.name);
|
||||
private inflight = new Map<string, Promise<DdragonManifest>>();
|
||||
|
||||
constructor(private readonly garnetService: GarnetService) {}
|
||||
|
||||
public async getManifest(locale: string = DEFAULT_LOCALE): Promise<DdragonManifest> {
|
||||
const normalizedLocale = normalizeLocale(locale);
|
||||
const cacheKey = manifestCacheKey(normalizedLocale);
|
||||
|
||||
const cached = await this.garnetService.getJson<DdragonManifest>(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.garnetService.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<DdragonManifest> {
|
||||
const version = await this.fetchLatestVersion();
|
||||
const [champions, summonerSpells, runesReforged] = await Promise.all([
|
||||
this.fetchChampionMap(version, locale),
|
||||
this.fetchSummonerSpellMap(version, locale),
|
||||
this.fetchRuneStyles(version, locale),
|
||||
]);
|
||||
return {
|
||||
version,
|
||||
cdn: DDRAGON_CDN,
|
||||
locale,
|
||||
champions,
|
||||
summonerSpells,
|
||||
runesReforged,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchLatestVersion(): Promise<string> {
|
||||
const versions = await this.fetchJson<unknown>(`${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<Record<string, DdragonChampionEntry>> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`;
|
||||
const payload = await this.fetchJson<ChampionDataResponse>(url);
|
||||
if (!payload || typeof payload !== 'object' || !payload.data) {
|
||||
throw new Error(`ddragon champion.json response is malformed (${url}).`);
|
||||
}
|
||||
|
||||
const map: Record<string, DdragonChampionEntry> = {};
|
||||
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<Record<string, DdragonSummonerSpellEntry>> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/summoner.json`;
|
||||
const payload = await this.fetchJson<SummonerSpellDataResponse>(url);
|
||||
if (!payload || typeof payload !== 'object' || !payload.data) {
|
||||
throw new Error(`ddragon summoner.json response is malformed (${url}).`);
|
||||
}
|
||||
|
||||
const map: Record<string, DdragonSummonerSpellEntry> = {};
|
||||
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 fetchRuneStyles(
|
||||
version: string,
|
||||
locale: string,
|
||||
): Promise<DdragonRuneStyleEntry[]> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`;
|
||||
const payload = await this.fetchJson<unknown>(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,
|
||||
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,
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchJson<T>(url: string): Promise<T> {
|
||||
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<RuneDataEntry>;
|
||||
return (
|
||||
typeof entry.id === 'number' &&
|
||||
typeof entry.key === 'string' &&
|
||||
typeof entry.icon === 'string' &&
|
||||
typeof entry.name === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
function manifestCacheKey(locale: string): string {
|
||||
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
|
||||
}
|
||||
Reference in new issue
Block a user