Add Riot API client

This commit is contained in:
dahyeon committed 2026-07-02 14:18:26 -07:00
1 parent 1f2805be23
commit 256d776131
6 files changed
+908

No files matched your search

@@ -0,0 +1,232 @@
import { SecretService } from '../global/secret/secret.service';
import {
RiotApiClient,
RiotApiKeyError,
RiotApiTimeoutError,
type RiotApiClientOptions,
RiotNotFoundError,
} from './riot-api.client';
import { RiotRateLimiter } from './riot-rate-limiter';
type FetchMock = jest.Mock<ReturnType<typeof fetch>, Parameters<typeof fetch>>;
type SleepMock = jest.Mock<Promise<void>, [number]>;
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
status: 200,
...init,
});
}
function createFetchMock(): FetchMock {
return jest.fn<ReturnType<typeof fetch>, Parameters<typeof fetch>>();
}
function createClient(
fetchMock: FetchMock,
options?: {
clientOptions?: Partial<RiotApiClientOptions>;
sleep?: SleepMock;
},
) {
const getSecret = jest
.fn<Promise<string>, [string]>()
.mockResolvedValue('RGAPI-test-key');
const waitForSlot = jest
.fn<Promise<void>, [string]>()
.mockResolvedValue(undefined);
const sleep =
options?.sleep ??
jest.fn<Promise<void>, [number]>().mockResolvedValue(undefined);
const secretService = {
get: getSecret,
} as unknown as SecretService;
const rateLimiter = {
waitForSlot,
} as unknown as RiotRateLimiter;
const clientOptions: RiotApiClientOptions = {
fetchFn: fetchMock,
sleep,
...options?.clientOptions,
};
const client = new RiotApiClient(secretService, rateLimiter, clientOptions);
return { client, getSecret, sleep, waitForSlot };
}
describe('RiotApiClient', () => {
it('fetches account data through the regional Riot ID endpoint with an API key header', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({
puuid: 'puuid-1',
gameName: 'Hide on bush',
tagLine: 'KR1',
}),
);
const { client, getSecret, waitForSlot } = createClient(fetchMock);
await expect(
client.getAccountByRiotId('Hide on bush', 'KR1', 'asia'),
).resolves.toEqual({
puuid: 'puuid-1',
gameName: 'Hide on bush',
tagLine: 'KR1',
});
expect(getSecret).toHaveBeenCalledWith('RIOT_API_KEY');
expect(waitForSlot).toHaveBeenCalledWith('asia');
const [requestUrl, requestInit] = fetchMock.mock.calls[0];
expect(requestUrl).toBe(
'https://asia.api.riotgames.com/riot/account/v1/accounts/by-riot-id/Hide%20on%20bush/KR1',
);
expect(requestInit?.headers).toEqual(
expect.objectContaining({
'X-Riot-Token': 'RGAPI-test-key',
}),
);
});
it('fetches platform and regional League endpoints with encoded parameters and query filters', async () => {
const fetchMock = createFetchMock()
.mockResolvedValueOnce(
jsonResponse({
id: 'summoner-1',
puuid: 'puuid/1',
profileIconId: 7,
summonerLevel: 30,
}),
)
.mockResolvedValueOnce(jsonResponse(['KR_1', 'KR_2']));
const { client } = createClient(fetchMock);
await client.getSummonerByPuuid('puuid/1', 'kr');
await expect(
client.getMatchIds('puuid/1', {
regionalRoute: 'asia',
queue: 420,
start: 0,
count: 20,
}),
).resolves.toEqual(['KR_1', 'KR_2']);
expect(fetchMock).toHaveBeenNthCalledWith(
1,
'https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/puuid%2F1',
expect.any(Object),
);
expect(fetchMock).toHaveBeenNthCalledWith(
2,
'https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/puuid%2F1/ids?queue=420&start=0&count=20',
expect.any(Object),
);
});
it('honors Retry-After for 429 responses and retries', async () => {
const sleep = jest
.fn<Promise<void>, [number]>()
.mockResolvedValue(undefined);
const fetchMock = createFetchMock()
.mockResolvedValueOnce(
jsonResponse(
{ status: { message: 'rate limited' } },
{
status: 429,
headers: { 'retry-after': '2' },
},
),
)
.mockResolvedValueOnce(jsonResponse(['KR_1']));
const { client } = createClient(fetchMock, { sleep });
await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']);
expect(sleep).toHaveBeenCalledWith(2000);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('caps oversized Retry-After waits before retrying', async () => {
const sleep = jest
.fn<Promise<void>, [number]>()
.mockResolvedValue(undefined);
const fetchMock = createFetchMock()
.mockResolvedValueOnce(
jsonResponse(
{ status: { message: 'rate limited' } },
{
status: 429,
headers: { 'retry-after': '9999' },
},
),
)
.mockResolvedValueOnce(jsonResponse(['KR_1']));
const { client } = createClient(fetchMock, { sleep });
await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']);
expect(sleep).toHaveBeenCalledWith(30_000);
});
it('fails 401 and 403 responses without retrying or leaking the API key', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({ status: { message: 'Forbidden' } }, { status: 403 }),
);
const { client } = createClient(fetchMock);
await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiKeyError);
await expect(client.getMatch('KR_1')).rejects.not.toThrow('RGAPI-test-key');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('maps 404 responses to a domain not-found error', async () => {
const fetchMock = createFetchMock().mockResolvedValue(
jsonResponse({ status: { message: 'not found' } }, { status: 404 }),
);
const { client } = createClient(fetchMock);
await expect(client.getAccountByRiotId('Missing', 'KR1')).rejects.toThrow(
RiotNotFoundError,
);
});
it('aborts a stalled Riot request with a domain timeout error', async () => {
const fetchMock: FetchMock = jest.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('aborted', 'AbortError'));
});
}),
);
const { client } = createClient(fetchMock, {
clientOptions: { requestTimeoutMs: 1 },
});
await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiTimeoutError);
});
it('validates minimal match and timeline response invariants', async () => {
const fetchMock = createFetchMock()
.mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} }))
.mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} }));
const { client } = createClient(fetchMock);
await expect(client.getMatch('KR_1')).resolves.toEqual({
metadata: {},
info: {},
});
await expect(client.getMatchTimeline('KR_1')).resolves.toEqual({
metadata: {},
info: {},
});
});
it('rejects malformed match payloads before analytics can consume them', async () => {
const fetchMock = createFetchMock().mockResolvedValue(jsonResponse({}));
const { client } = createClient(fetchMock);
await expect(client.getMatch('KR_1')).rejects.toThrow(
'Riot match response was missing object field "metadata".',
);
});
});