import { Inject, Injectable, Optional } from '@nestjs/common'; import { SecretService } from '../global/secret/secret.service'; import { RIOT_PLATFORM_ROUTES, RIOT_REGIONAL_ROUTES, type RiotPlatformRoute, type RiotRegionalRoute, } from './riot.types'; import { RiotRateLimiter } from './riot-rate-limiter'; export const RIOT_API_CLIENT_OPTIONS = Symbol('RIOT_API_CLIENT_OPTIONS'); type FetchFunction = typeof fetch; export interface RiotApiClientOptions { baseBackoffMs?: number; maxRetryAfterMs?: number; fetchFn?: FetchFunction; requestTimeoutMs?: number; maxRetries?: number; sleep?: (durationMs: number) => Promise; } export interface RiotAccountDto { puuid: string; gameName: string; tagLine: string; } export interface RiotSummonerDto { profileIconId: number; puuid: string; revisionDate?: number; summonerLevel: number; } export interface RiotLeagueEntryDto { freshBlood: boolean; hotStreak: boolean; inactive: boolean; leagueId: string; leaguePoints: number; losses: number; queueType: string; rank: string; tier: string; veteran: boolean; wins: number; } export interface RiotMatchIdsParams { count?: number; queue?: number; regionalRoute?: RiotRegionalRoute; start?: number; } export class RiotApiError extends Error { constructor( message: string, public readonly statusCode?: number, public readonly code = 'RIOT_API_ERROR', ) { super(message); this.name = new.target.name; } } export class RiotApiKeyError extends RiotApiError { constructor(statusCode: number) { super( 'Riot API key is missing, expired, or invalid. Regenerate the key in the Riot Developer Portal and update Infisical RIOT_API_KEY.', statusCode, 'RIOT_API_KEY_INVALID', ); } } export class RiotNotFoundError extends RiotApiError { constructor(statusCode: number) { super('Riot API resource was not found.', statusCode, 'RIOT_NOT_FOUND'); } } export class RiotApiTimeoutError extends RiotApiError { constructor() { super('Riot API request timed out.', undefined, 'RIOT_API_TIMEOUT'); } } const DEFAULT_MAX_RETRIES = 3; const DEFAULT_BASE_BACKOFF_MS = 250; const DEFAULT_MAX_RETRY_AFTER_MS = 30_000; const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; function defaultSleep(durationMs: number): Promise { return new Promise((resolve) => setTimeout(resolve, durationMs)); } function assertAllowedRoute( route: RiotPlatformRoute | RiotRegionalRoute, ): void { if ( !RIOT_PLATFORM_ROUTES.includes(route as RiotPlatformRoute) && !RIOT_REGIONAL_ROUTES.includes(route as RiotRegionalRoute) ) { throw new RiotApiError('Unsupported Riot routing value.'); } } function regionalBaseUrl(regionalRoute: RiotRegionalRoute): string { assertAllowedRoute(regionalRoute); return `https://${regionalRoute}.api.riotgames.com`; } function platformBaseUrl(platformRoute: RiotPlatformRoute): string { assertAllowedRoute(platformRoute); return `https://${platformRoute}.api.riotgames.com`; } function encodePathValue(value: string): string { return encodeURIComponent(value); } export function parseRetryAfterMs( retryAfter: string | null, now = Date.now(), ): number | undefined { const trimmed = retryAfter?.trim(); if (!trimmed) return undefined; const retryAfterSeconds = Number(trimmed); if (Number.isFinite(retryAfterSeconds)) { return Math.max(0, retryAfterSeconds * 1000); } const retryAt = Date.parse(trimmed); if (Number.isNaN(retryAt)) return undefined; return Math.max(0, retryAt - now); } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } function requireRecord(value: unknown, endpointName: string) { if (!isRecord(value)) { throw new RiotApiError( `Riot ${endpointName} response had an unexpected shape.`, ); } return value; } function requireRecordField( record: Record, key: string, endpointName: string, ): Record { const value = record[key]; if (!isRecord(value)) { throw new RiotApiError( `Riot ${endpointName} response was missing object field "${key}".`, ); } return value; } function requireString( record: Record, key: string, endpointName: string, ): string { const value = record[key]; if (typeof value !== 'string') { throw new RiotApiError( `Riot ${endpointName} response was missing string field "${key}".`, ); } return value; } function numberOrFallback( record: Record, key: string, fallback: number, ): number { const value = record[key]; return typeof value === 'number' ? value : fallback; } function optionalNumber( record: Record, key: string, ): number | undefined { const value = record[key]; return typeof value === 'number' ? value : undefined; } function optionalBoolean( record: Record, key: string, fallback: boolean, ) { const value = record[key]; return typeof value === 'boolean' ? value : fallback; } @Injectable() export class RiotApiClient { private readonly baseBackoffMs: number; private readonly fetchFn: FetchFunction; private readonly maxRetryAfterMs: number; private readonly maxRetries: number; private readonly requestTimeoutMs: number; private readonly sleep: (durationMs: number) => Promise; constructor( private readonly secretService: SecretService, private readonly rateLimiter: RiotRateLimiter, @Optional() @Inject(RIOT_API_CLIENT_OPTIONS) options: RiotApiClientOptions = {}, ) { this.baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS; this.fetchFn = options.fetchFn ?? fetch; this.maxRetryAfterMs = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS; this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES; this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; this.sleep = options.sleep ?? defaultSleep; } public async getAccountByRiotId( gameName: string, tagLine: string, regionalRoute: RiotRegionalRoute = 'asia', ): Promise { const response = await this.requestJson( regionalRoute, `${regionalBaseUrl(regionalRoute)}/riot/account/v1/accounts/by-riot-id/${encodePathValue(gameName)}/${encodePathValue(tagLine)}`, ); return this.parseAccount(response); } public async getSummonerByPuuid( puuid: string, platformRoute: RiotPlatformRoute = 'kr', ): Promise { const response = await this.requestJson( platformRoute, `${platformBaseUrl(platformRoute)}/lol/summoner/v4/summoners/by-puuid/${encodePathValue(puuid)}`, ); return this.parseSummoner(response); } public async getLeagueEntriesByPuuid( puuid: string, platformRoute: RiotPlatformRoute = 'kr', ): Promise { const response = await this.requestJson( platformRoute, `${platformBaseUrl(platformRoute)}/lol/league/v4/entries/by-puuid/${encodePathValue(puuid)}`, ); return this.parseLeagueEntries(response); } public async getMatchIds( puuid: string, params: RiotMatchIdsParams = {}, ): Promise { const regionalRoute = params.regionalRoute ?? 'asia'; const searchParams = new URLSearchParams(); if (params.queue !== undefined) searchParams.set('queue', String(params.queue)); if (params.start !== undefined) searchParams.set('start', String(params.start)); if (params.count !== undefined) searchParams.set('count', String(params.count)); const query = searchParams.size > 0 ? `?${searchParams.toString()}` : ''; const response = await this.requestJson( regionalRoute, `${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/by-puuid/${encodePathValue(puuid)}/ids${query}`, ); return this.parseMatchIds(response); } public async getMatch( matchId: string, regionalRoute: RiotRegionalRoute = 'asia', ): Promise> { const response = await this.requestJson( regionalRoute, `${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}`, ); return this.parseMatchPayload(response, 'match'); } public async getMatchTimeline( matchId: string, regionalRoute: RiotRegionalRoute = 'asia', ): Promise> { const response = await this.requestJson( regionalRoute, `${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}/timeline`, ); return this.parseMatchPayload(response, 'match timeline'); } private async requestJson( routingValue: RiotPlatformRoute | RiotRegionalRoute, url: string, ): Promise { const apiKey = await this.secretService.get('RIOT_API_KEY'); for (let attemptIndex = 0; ; attemptIndex += 1) { await this.rateLimiter.waitForSlot(routingValue); const response = await this.fetchWithTimeout(url, apiKey); if (response.status === 429 && attemptIndex < this.maxRetries) { const rawRetryAfterMs = parseRetryAfterMs(response.headers.get('retry-after')) ?? this.exponentialBackoffMs(attemptIndex); const retryAfterMs = Math.min(rawRetryAfterMs, this.maxRetryAfterMs); await this.sleep(retryAfterMs); continue; } if (response.status >= 500 && attemptIndex < this.maxRetries) { await this.sleep(this.exponentialBackoffMs(attemptIndex)); continue; } if (response.status === 401 || response.status === 403) { throw new RiotApiKeyError(response.status); } if (response.status === 404) { throw new RiotNotFoundError(response.status); } if (!response.ok) { throw new RiotApiError( `Riot API request failed with status ${response.status}.`, response.status, ); } return response.json(); } } private exponentialBackoffMs(attemptIndex: number): number { return this.baseBackoffMs * 2 ** attemptIndex; } private async fetchWithTimeout( url: string, apiKey: string, ): Promise { const abortController = new AbortController(); const timeout = setTimeout( () => abortController.abort(), this.requestTimeoutMs, ); try { return await this.fetchFn(url, { headers: { Accept: 'application/json', 'X-Riot-Token': apiKey, }, signal: abortController.signal, }); } catch (error) { if ( error instanceof DOMException && error.name.toLowerCase() === 'aborterror' ) { throw new RiotApiTimeoutError(); } throw error; } finally { clearTimeout(timeout); } } private parseAccount(value: unknown): RiotAccountDto { const record = requireRecord(value, 'account'); return { puuid: requireString(record, 'puuid', 'account'), gameName: requireString(record, 'gameName', 'account'), tagLine: requireString(record, 'tagLine', 'account'), }; } private parseSummoner(value: unknown): RiotSummonerDto { const record = requireRecord(value, 'summoner'); return { puuid: requireString(record, 'puuid', 'summoner'), profileIconId: numberOrFallback(record, 'profileIconId', 0), revisionDate: optionalNumber(record, 'revisionDate'), summonerLevel: numberOrFallback(record, 'summonerLevel', 0), }; } private parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] { if (!Array.isArray(value)) { throw new RiotApiError( 'Riot league entries response had an unexpected shape.', ); } return value.map((entry) => { const record = requireRecord(entry, 'league entry'); return { leagueId: requireString(record, 'leagueId', 'league entry'), queueType: requireString(record, 'queueType', 'league entry'), tier: requireString(record, 'tier', 'league entry'), rank: requireString(record, 'rank', 'league entry'), leaguePoints: numberOrFallback(record, 'leaguePoints', 0), wins: numberOrFallback(record, 'wins', 0), losses: numberOrFallback(record, 'losses', 0), veteran: optionalBoolean(record, 'veteran', false), inactive: optionalBoolean(record, 'inactive', false), freshBlood: optionalBoolean(record, 'freshBlood', false), hotStreak: optionalBoolean(record, 'hotStreak', false), }; }); } private parseMatchIds(value: unknown): string[] { if (!Array.isArray(value)) { throw new RiotApiError('Riot match id response had an unexpected shape.'); } const matchIds = value.filter( (matchId): matchId is string => typeof matchId === 'string', ); if (matchIds.length !== value.length) { throw new RiotApiError('Riot match id response had an unexpected shape.'); } return matchIds; } private parseMatchPayload( value: unknown, endpointName: string, ): Record { const record = requireRecord(value, endpointName); requireRecordField(record, 'metadata', endpointName); requireRecordField(record, 'info', endpointName); return record; } }