import { Injectable, Logger } from '@nestjs/common'; import { SecretService } from '../global/secret/secret.service'; import { RiotApiErrorBody, RiotPlatformRoute, RiotRegionalRoute, RiotRequestOptions, RiotResponseParser, } from './riot.types'; import { RiotRateLimiterService } from './riot-rate-limiter.service'; const RIOT_REGION_BASE_URLS: Record = { americas: 'https://americas.api.riotgames.com', asia: 'https://asia.api.riotgames.com', europe: 'https://europe.api.riotgames.com', sea: 'https://sea.api.riotgames.com', }; const RIOT_PLATFORM_BASE_URLS: Record = { br1: 'https://br1.api.riotgames.com', eun1: 'https://eun1.api.riotgames.com', euw1: 'https://euw1.api.riotgames.com', jp1: 'https://jp1.api.riotgames.com', kr: 'https://kr.api.riotgames.com', la1: 'https://la1.api.riotgames.com', la2: 'https://la2.api.riotgames.com', me1: 'https://me1.api.riotgames.com', na1: 'https://na1.api.riotgames.com', oc1: 'https://oc1.api.riotgames.com', ph2: 'https://ph2.api.riotgames.com', ru: 'https://ru.api.riotgames.com', sg2: 'https://sg2.api.riotgames.com', th2: 'https://th2.api.riotgames.com', tr1: 'https://tr1.api.riotgames.com', tw2: 'https://tw2.api.riotgames.com', vn2: 'https://vn2.api.riotgames.com', }; export class RiotApiError extends Error { constructor( message: string, public readonly status: number, public readonly url: string, public readonly body?: RiotApiErrorBody, public readonly retryAfterSeconds?: number, ) { super(message); } } @Injectable() export class RiotClientService { private readonly logger = new Logger(RiotClientService.name); constructor( private readonly secretService: SecretService, private readonly rateLimiter: RiotRateLimiterService, ) {} public async get( path: string, options: RiotRequestOptions = {}, parser?: RiotResponseParser, ): Promise { const apiKey = await this.secretService.get('RIOT_API_KEY'); const url = this.buildUrl(path, options); const routeKey = options.platform ?? options.region ?? 'asia'; return this.fetchWithRetry(url, apiKey, options.signal, parser, routeKey); } private buildUrl(path: string, options: RiotRequestOptions): string { const baseUrl = options.platform ? RIOT_PLATFORM_BASE_URLS[options.platform] : RIOT_REGION_BASE_URLS[options.region ?? 'asia']; const normalizedPath = path.startsWith('/') ? path : `/${path}`; const url = new URL(`${baseUrl}${normalizedPath}`); if (options.query) { for (const [key, value] of Object.entries(options.query)) { if (value === undefined) { continue; } url.searchParams.set(key, String(value)); } } return url.toString(); } private async createApiError( response: Response, url: string, ): Promise { let body: RiotApiErrorBody | undefined; try { body = (await response.json()) as RiotApiErrorBody; } catch { body = undefined; } const message = body?.status?.message ?? `Riot API request failed with status ${response.status}`; const retryAfterHeader = response.headers.get('Retry-After'); const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : undefined; this.logger.warn(`${message} (${response.status}) ${url}`); return new RiotApiError( message, response.status, url, body, Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined, ); } private async fetchWithRetry( url: string, apiKey: string, signal: AbortSignal | undefined, parser: RiotResponseParser | undefined, routeKey: RiotRegionalRoute | RiotPlatformRoute, attempt = 0, ): Promise { await this.rateLimiter.acquire(routeKey); const response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json', 'X-Riot-Token': apiKey, }, signal, }); const appRateLimitCount = response.headers.get('X-App-Rate-Limit-Count'); if (appRateLimitCount && Math.random() < 0.05) { this.logger.debug(`Riot rate usage ${routeKey}: ${appRateLimitCount}`); } if (!response.ok) { const error = await this.createApiError(response, url); if ( error.status === 429 && attempt === 0 ) { await sleep((error.retryAfterSeconds ?? 1) * 1000); return this.fetchWithRetry( url, apiKey, signal, parser, routeKey, attempt + 1, ); } throw error; } if (response.status === 204) { return undefined as T; } const payload = (await response.json()) as unknown; return parser ? parser(payload) : (payload as T); } } function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); }