This commit is contained in:
dahyeon committed 2026-04-26 03:33:24 -07:00
1 parent 6d62de4ec4
commit 285f72b3ee
16 files changed
+2095 -136

No files matched your search

@@ -7,6 +7,7 @@ import {
RiotRequestOptions,
RiotResponseParser,
} from './riot.types';
import { RiotRateLimiterService } from './riot-rate-limiter.service';
const RIOT_REGION_BASE_URLS: Record<RiotRegionalRoute, string> = {
americas: 'https://americas.api.riotgames.com',
@@ -51,7 +52,10 @@ export class RiotApiError extends Error {
export class RiotClientService {
private readonly logger = new Logger(RiotClientService.name);
constructor(private readonly secretService: SecretService) {}
constructor(
private readonly secretService: SecretService,
private readonly rateLimiter: RiotRateLimiterService,
) {}
public async get<T>(
path: string,
@@ -60,31 +64,9 @@ export class RiotClientService {
): Promise<T> {
const apiKey = await this.secretService.get<string>('RIOT_API_KEY');
const url = this.buildUrl(path, options);
const routeKey = options.platform ?? options.region ?? 'asia';
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;
return this.fetchWithRetry(url, apiKey, options.signal, parser, routeKey);
}
private buildUrl(path: string, options: RiotRequestOptions): string {
@@ -137,4 +119,60 @@ export class RiotClientService {
Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined,
);
}
private async fetchWithRetry<T>(
url: string,
apiKey: string,
signal: AbortSignal | undefined,
parser: RiotResponseParser<T> | undefined,
routeKey: RiotRegionalRoute | RiotPlatformRoute,
attempt = 0,
): Promise<T> {
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 &&
error.retryAfterSeconds !== undefined
) {
await sleep(error.retryAfterSeconds * 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<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}