diff --git a/apps/api/src/modules/riot/riot.client.service.ts b/apps/api/src/modules/riot/riot.client.service.ts new file mode 100644 index 00000000..b7b08f37 --- /dev/null +++ b/apps/api/src/modules/riot/riot.client.service.ts @@ -0,0 +1,118 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { SecretService } from '../global/secret/secret.service'; +import { + RiotApiErrorBody, + RiotRegionalRoute, + RiotRequestOptions, + RiotResponseParser, +} from './riot.types'; + +const RIOT_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', +}; + +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) {} + + 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 response = await fetch(url, { + method: 'GET', + headers: { + Accept: 'application/json', + 'X-Riot-Token': apiKey, + }, + signal: options.signal, + }); + + if (!response.ok) { + throw await this.createApiError(response, url); + } + + if (response.status === 204) { + return undefined as T; + } + + const payload = (await response.json()) as unknown; + + if (parser) { + return parser(payload); + } + + return payload as T; + } + + private buildUrl(path: string, options: RiotRequestOptions): string { + const region = options.region ?? 'asia'; + const baseUrl = RIOT_BASE_URLS[region]; + 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, + ); + } +}