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, Parameters>; type SleepMock = jest.Mock, [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, Parameters>(); } function createClient( fetchMock: FetchMock, options?: { clientOptions?: Partial; sleep?: SleepMock; }, ) { const getSecret = jest .fn, [string]>() .mockResolvedValue('RGAPI-test-key'); const waitForSlot = jest .fn, [string]>() .mockResolvedValue(undefined); const sleep = options?.sleep ?? jest.fn, [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({ profileIconId: 7, puuid: 'puuid/1', 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('accepts current Summoner-V4 by-puuid responses', async () => { const fetchMock = createFetchMock().mockResolvedValue( jsonResponse({ profileIconId: 7, puuid: 'puuid-1', revisionDate: 1_783_056_144_000, summonerLevel: 30, }), ); const { client } = createClient(fetchMock); await expect(client.getSummonerByPuuid('puuid-1', 'kr')).resolves.toEqual({ profileIconId: 7, puuid: 'puuid-1', revisionDate: 1_783_056_144_000, summonerLevel: 30, }); }); it('accepts current League-V4 by-puuid entries without league ids', async () => { const fetchMock = createFetchMock().mockResolvedValue( jsonResponse([ { queueType: 'RANKED_SOLO_5x5', tier: 'DIAMOND', rank: 'IV', puuid: 'puuid-1', leaguePoints: 0, wins: 164, losses: 152, veteran: false, inactive: false, freshBlood: false, hotStreak: false, }, ]), ); const { client } = createClient(fetchMock); await expect( client.getLeagueEntriesByPuuid('puuid-1', 'kr'), ).resolves.toEqual([ { queueType: 'RANKED_SOLO_5x5', tier: 'DIAMOND', rank: 'IV', leaguePoints: 0, wins: 164, losses: 152, veteran: false, inactive: false, freshBlood: false, hotStreak: false, }, ]); }); it('fetches apex League-V4 lists by queue without legacy summoner ids', async () => { const fetchMock = createFetchMock().mockResolvedValue( jsonResponse({ tier: 'CHALLENGER', queue: 'RANKED_SOLO_5x5', entries: [ { puuid: 'seed-puuid-1', leaguePoints: 1200, rank: 'I', wins: 300, losses: 210, veteran: true, inactive: false, freshBlood: false, hotStreak: true, }, ], }), ); const { client, waitForSlot } = createClient(fetchMock); await expect( client.getChallengerLeagueByQueue('RANKED_SOLO_5x5', 'kr'), ).resolves.toEqual({ tier: 'CHALLENGER', queueType: 'RANKED_SOLO_5x5', entries: [ { puuid: 'seed-puuid-1', tier: 'CHALLENGER', queueType: 'RANKED_SOLO_5x5', rank: 'I', leaguePoints: 1200, wins: 300, losses: 210, veteran: true, inactive: false, freshBlood: false, hotStreak: true, }, ], }); expect(waitForSlot).toHaveBeenCalledWith('kr'); expect(fetchMock).toHaveBeenCalledWith( 'https://kr.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5', expect.any(Object), ); }); it('rejects apex League-V4 list entries without puuid', async () => { const fetchMock = createFetchMock().mockResolvedValue( jsonResponse({ tier: 'MASTER', queue: 'RANKED_SOLO_5x5', entries: [ { leaguePoints: 200, rank: 'I', wins: 120, losses: 100, }, ], }), ); const { client } = createClient(fetchMock); await expect( client.getMasterLeagueByQueue('RANKED_SOLO_5x5', 'kr'), ).rejects.toThrow( 'Riot apex league entry response was missing string field "puuid".', ); }); it('honors Retry-After for 429 responses and retries', async () => { const sleep = jest .fn, [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, [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((_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".', ); }); });