feat(riot): implement generic Riot API client service

This commit is contained in:
dahyeon committed 2026-04-15 01:35:11 +09:00
1 parent e850f0d9bb
commit f917120363
1 file changed
+118
@@ -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<RiotRegionalRoute, string> = {
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<T>(
path: string,
options: RiotRequestOptions = {},
parser?: RiotResponseParser<T>,
): Promise<T> {
const apiKey = await this.secretService.get<string>('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<RiotApiError> {
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,
);
}
}