From 3e7a73c52897d604c87ea6357eb6b7ba13a546b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tr=C3=A8sAbhi?= <43380238+tresabhi@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:19:25 -0500 Subject: [PATCH] feat: cleaner fetch blitz func --- src/app/embeds/session/page.tsx | 13 +++++------ src/app/tools/rating/page.tsx | 5 ++-- src/commands/searchClans.ts | 12 +++++----- src/commands/searchPlayers.ts | 14 +++++------ src/core/blitz/fetchBlitz.ts | 16 +++++++++++-- src/core/blitz/getAccountAchievements.ts | 7 +++--- src/core/blitz/getAccountInfo.ts | 10 ++++---- src/core/blitz/getClanAccountInfo.ts | 13 ++++++----- src/core/blitz/getClanInfo.ts | 9 +++----- src/core/blitz/getTankStats.ts | 16 ++++--------- src/core/blitz/searchClansAcrossRegions.ts | 22 ++++++++++-------- .../blitz/searchPlayersAcrossRegions/index.ts | 23 ++++++++++--------- src/core/blitzkrieg/setSession.ts | 7 ++---- 13 files changed, 82 insertions(+), 85 deletions(-) diff --git a/src/app/embeds/session/page.tsx b/src/app/embeds/session/page.tsx index 0d724f360..e3dc9cacb 100644 --- a/src/app/embeds/session/page.tsx +++ b/src/app/embeds/session/page.tsx @@ -3,7 +3,6 @@ import { ContextMenu } from '@radix-ui/themes'; import { useEffect, useState } from 'react'; import * as Breakdown from '../../../components/Breakdown'; -import { WARGAMING_APPLICATION_ID } from '../../../constants/wargamingApplicationID'; import fetchBlitz from '../../../core/blitz/fetchBlitz'; import { resetSession } from '../../../core/blitzkrieg/resetSession'; import { @@ -88,10 +87,10 @@ export default function SessionPage({ naked = true }: SessionPageProps) { async function recalculateDiff() { if (session.isTracking) { const { id, region } = session; - const careerRaw = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/tanks/stats/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${id}`, - ); - const career = careerRaw[id].reduce< + const careerRaw = await fetchBlitz(region, 'tanks/stats', { + account_id: id, + }); + const career = careerRaw[id]!.reduce< Record >( (accumulator, curr) => ({ @@ -103,7 +102,7 @@ export default function SessionPage({ naked = true }: SessionPageProps) { const awaitedTankDefinitions = await tankDefinitions; const awaitedTankAverages = await tankAverages; const careerWN8 = - careerRaw[id].reduce( + careerRaw[id]!.reduce( (accumulator, { tank_id, all }) => accumulator + (awaitedTankAverages[tank_id] && all.battles > 0 @@ -112,7 +111,7 @@ export default function SessionPage({ naked = true }: SessionPageProps) { : 0), 0, ) / - careerRaw[id].reduce( + careerRaw[id]!.reduce( (accumulator, { tank_id, all }) => accumulator + (awaitedTankAverages[tank_id] && all.battles > 0 diff --git a/src/app/tools/rating/page.tsx b/src/app/tools/rating/page.tsx index 14d47255d..2dd70856f 100644 --- a/src/app/tools/rating/page.tsx +++ b/src/app/tools/rating/page.tsx @@ -25,7 +25,6 @@ import { Region, UNLOCALIZED_REGION_NAMES, } from '../../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../../constants/wargamingApplicationID'; import fetchBlitz from '../../../core/blitz/fetchBlitz'; import { getClanAccountInfo } from '../../../core/blitz/getClanAccountInfo'; import getRatingInfo from '../../../core/blitz/getRatingInfo'; @@ -818,7 +817,9 @@ export default function Page() { } else { setSearchLoading(true); const accountList = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/account/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${encodedSearch}`, + region, + 'account/list', + { search: encodedSearch }, ); const playerKeys = Object.keys( leaderboard[region][season], diff --git a/src/commands/searchClans.ts b/src/commands/searchClans.ts index 3fe09224a..2307ad249 100644 --- a/src/commands/searchClans.ts +++ b/src/commands/searchClans.ts @@ -1,7 +1,6 @@ import { Locale } from 'discord.js'; import markdownEscape from 'markdown-escape'; import { Region } from '../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../constants/wargamingApplicationID'; import fetchBlitz from '../core/blitz/fetchBlitz'; import addClanChoices from '../core/discord/addClanChoices'; import addRegionChoices from '../core/discord/addRegionChoices'; @@ -49,17 +48,18 @@ export const searchClansCommand = new Promise((resolve) => { async handler(interaction) { const { translate } = translator(interaction.locale); - const server = interaction.options.getString('region') as Region; + const region = interaction.options.getString('region') as Region; const clan = interaction.options.getString('clan')!; const limit = interaction.options.getInteger('limit') ?? DEFAULT_LIMIT; - const clanList = await fetchBlitz( - `https://api.wotblitz.${server}/wotb/clans/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${clan}&limit=${limit}`, - ); + const clanList = await fetchBlitz(region, 'clans/list', { + search: clan, + limit, + }); return embedInfo( translate('bot.commands.search_clans.body.title', [ markdownEscape(clan), - translate(`common.regions.normal.${server}`), + translate(`common.regions.normal.${region}`), ]), clanList.length === 0 ? translate('bot.commands.search_clans.body.no_results') diff --git a/src/commands/searchPlayers.ts b/src/commands/searchPlayers.ts index ed816c1f2..5be8c4f5b 100644 --- a/src/commands/searchPlayers.ts +++ b/src/commands/searchPlayers.ts @@ -1,7 +1,6 @@ import { Locale } from 'discord.js'; import markdownEscape from 'markdown-escape'; import { Region } from '../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../constants/wargamingApplicationID'; import fetchBlitz from '../core/blitz/fetchBlitz'; import { AccountList } from '../core/blitz/searchPlayersAcrossRegions'; import { usernamePattern } from '../core/blitz/searchPlayersAcrossRegions/constants'; @@ -50,22 +49,21 @@ export const searchPlayersCommand = new Promise((resolve) => { async handler(interaction) { const { translate } = translator(interaction.locale); - const server = interaction.options.getString('region') as Region; + const region = interaction.options.getString('region') as Region; const name = interaction.options.getString('username')!; const limit = interaction.options.getInteger('limit') ?? 25; const trimmedSearch = name.trim(); const players = usernamePattern.test(trimmedSearch) - ? await fetchBlitz( - `https://api.wotblitz.${server}/wotb/account/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${encodeURIComponent( - trimmedSearch, - )}&limit=${limit}`, - ) + ? await fetchBlitz(region, 'account/list', { + search: trimmedSearch, + limit, + }) : []; return embedInfo( translate('bot.commands.search_players.body.title', [ markdownEscape(trimmedSearch), - translate(`common.regions.normal.${server}`), + translate(`common.regions.normal.${region}`), ]), `\`\`\`${ players.length === 0 diff --git a/src/core/blitz/fetchBlitz.ts b/src/core/blitz/fetchBlitz.ts index 5c3a17bcb..cc2df8816 100644 --- a/src/core/blitz/fetchBlitz.ts +++ b/src/core/blitz/fetchBlitz.ts @@ -1,3 +1,5 @@ +import { Region } from '../../constants/regions'; +import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import { patientFetch } from '../blitzkrieg/patientFetch'; type BlitzResponse = @@ -58,10 +60,20 @@ async function manageQueue() { } } -export default function fetchBlitz(url: string) { +export default function fetchBlitz( + region: Region, + path: string, + params: Record = {}, +) { return new Promise((resolve) => { queue.push({ - url, + url: `https://api.wotblitz.${region}/wotb/${path}/?${Object.entries({ + application_id: WARGAMING_APPLICATION_ID, + ...params, + }) + .filter(([_, value]) => value !== undefined) + .map(([key, value]) => `${key}=${encodeURIComponent(value!)}`) + .join('&')}`, resolve(data) { resolve(data as Data); }, diff --git a/src/core/blitz/getAccountAchievements.ts b/src/core/blitz/getAccountAchievements.ts index 98b7c9cfd..c87e34118 100644 --- a/src/core/blitz/getAccountAchievements.ts +++ b/src/core/blitz/getAccountAchievements.ts @@ -1,5 +1,4 @@ import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import fetchBlitz from './fetchBlitz'; import { normalizeIds } from './normalizeIds'; @@ -23,9 +22,9 @@ export async function getAccountAchievements< : IndividualAccountAchievements[], >(region: Region, ids: Ids) { const object = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/account/achievements/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${normalizeIds( - ids, - )}`, + region, + 'account/achievements', + { account_id: normalizeIds(ids) }, ); if (typeof ids === 'number') { diff --git a/src/core/blitz/getAccountInfo.ts b/src/core/blitz/getAccountInfo.ts index e9cab4285..51f602f0c 100644 --- a/src/core/blitz/getAccountInfo.ts +++ b/src/core/blitz/getAccountInfo.ts @@ -1,5 +1,4 @@ import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import fetchBlitz from './fetchBlitz'; import { normalizeIds } from './normalizeIds'; @@ -97,11 +96,10 @@ export async function getAccountInfo< ? IndividualAccountInfo : IndividualAccountInfo[], >(region: Region, ids: Ids, extra: string[] = []) { - const object = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/account/info/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${normalizeIds( - ids, - )}${extra.length === 0 ? '' : `&extra=${extra.join(',')}`}`, - ); + const object = await fetchBlitz(region, 'account/info', { + account_id: normalizeIds(ids), + extra: extra.length === 0 ? undefined : extra.join(','), + }); if (typeof ids === 'number') { return object[ids as number] as ReturnType; diff --git a/src/core/blitz/getClanAccountInfo.ts b/src/core/blitz/getClanAccountInfo.ts index de5a73cf4..0a986eac7 100644 --- a/src/core/blitz/getClanAccountInfo.ts +++ b/src/core/blitz/getClanAccountInfo.ts @@ -1,7 +1,5 @@ import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import fetchBlitz from './fetchBlitz'; -import { normalizeExtra } from './normalizeExtra'; import { normalizeIds } from './normalizeIds'; type IndividualClanAccountInfo = { @@ -30,11 +28,14 @@ export async function getClanAccountInfo< ReturnType = Ids extends number ? IndividualClanAccountInfo : IndividualClanAccountInfo[], ->(region: Region, ids: Ids, extra?: string[]) { +>(region: Region, ids: Ids, extra: string[] = []) { const object = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/clans/accountinfo/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${normalizeIds( - ids, - )}${normalizeExtra(extra)}`, + region, + 'clans/accountinfo', + { + account_id: normalizeIds(ids), + extra: extra.length === 0 ? undefined : extra.join(','), + }, ); if (typeof ids === 'number') { diff --git a/src/core/blitz/getClanInfo.ts b/src/core/blitz/getClanInfo.ts index e61a828c2..9ac36d92d 100644 --- a/src/core/blitz/getClanInfo.ts +++ b/src/core/blitz/getClanInfo.ts @@ -1,5 +1,4 @@ import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import fetchBlitz from './fetchBlitz'; import { normalizeIds } from './normalizeIds'; @@ -40,11 +39,9 @@ export async function getClanInfo< Ids extends number | number[], ReturnType = Ids extends number ? IndividualClanInfo : IndividualClanInfo[], >(region: Region, ids: Ids) { - const object = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/clans/info/?application_id=${WARGAMING_APPLICATION_ID}&clan_id=${normalizeIds( - ids, - )}`, - ); + const object = await fetchBlitz(region, 'clans/info', { + clan_id: normalizeIds(ids), + }); if (typeof ids === 'number') { return object[ids as number] as ReturnType; diff --git a/src/core/blitz/getTankStats.ts b/src/core/blitz/getTankStats.ts index d83af7a3f..060efc064 100644 --- a/src/core/blitz/getTankStats.ts +++ b/src/core/blitz/getTankStats.ts @@ -1,19 +1,11 @@ -import { Locale } from 'discord.js'; import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import { TanksStats } from '../../types/tanksStats'; -import { translator } from '../localization/translator'; import fetchBlitz from './fetchBlitz'; -export default async function getTankStats( - region: Region, - id: number, - locale: Locale, -) { - const { t } = translator(locale); - const tankStats = await fetchBlitz( - `https://api.wotblitz.${region}/wotb/tanks/stats/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${id}`, - ); +export default async function getTankStats(region: Region, id: number) { + const tankStats = await fetchBlitz(region, 'tanks/stats', { + account_id: id, + }); return tankStats[id]; } diff --git a/src/core/blitz/searchClansAcrossRegions.ts b/src/core/blitz/searchClansAcrossRegions.ts index de5e7a224..6d14f7e8d 100644 --- a/src/core/blitz/searchClansAcrossRegions.ts +++ b/src/core/blitz/searchClansAcrossRegions.ts @@ -1,5 +1,4 @@ import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import { ClanList } from '../../types/clanList'; import fetchBlitz from './fetchBlitz'; @@ -15,9 +14,10 @@ export default async function searchClansAcrossRegions( return ( await Promise.all([ - fetchBlitz( - `https://api.wotblitz.com/wotb/clans/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${search}&limit=${normalizedLimit}`, - ).then((value) => + fetchBlitz('com', 'clans/list', { + search, + limit: normalizedLimit, + }).then((value) => value .map((account) => ({ ...account, @@ -25,9 +25,10 @@ export default async function searchClansAcrossRegions( })) .splice(0, normalizedLimit), ), - fetchBlitz( - `https://api.wotblitz.eu/wotb/clans/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${search}&limit=${normalizedLimit}`, - ).then((value) => + fetchBlitz('eu', 'clans/list', { + search, + limit: normalizedLimit, + }).then((value) => value .map((account) => ({ ...account, @@ -35,9 +36,10 @@ export default async function searchClansAcrossRegions( })) .splice(0, normalizedLimit), ), - fetchBlitz( - `https://api.wotblitz.asia/wotb/clans/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${search}&limit=${normalizedLimit}`, - ).then((value) => + fetchBlitz('asia', 'clans/list', { + search, + limit: normalizedLimit, + }).then((value) => value .map((account) => ({ ...account, diff --git a/src/core/blitz/searchPlayersAcrossRegions/index.ts b/src/core/blitz/searchPlayersAcrossRegions/index.ts index 92c7d7ae9..8ca9130a7 100644 --- a/src/core/blitz/searchPlayersAcrossRegions/index.ts +++ b/src/core/blitz/searchPlayersAcrossRegions/index.ts @@ -1,5 +1,4 @@ import { Region } from '../../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../../constants/wargamingApplicationID'; import fetchBlitz from '../fetchBlitz'; import { usernamePattern } from './constants'; @@ -18,14 +17,14 @@ export default async function searchPlayersAcrossRegions( ) { const trimmedSearch = search.trim(); const normalizedLimit = Math.floor(limit / 3); - const encodedSearch = encodeURIComponent(trimmedSearch); if (usernamePattern.test(trimmedSearch)) { return ( await Promise.all([ - fetchBlitz( - `https://api.wotblitz.com/wotb/account/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${encodedSearch}&limit=${normalizedLimit}`, - ).then( + fetchBlitz('com', 'account/list', { + search, + limit: normalizedLimit, + }).then( (value) => value && value.map((account) => ({ @@ -33,9 +32,10 @@ export default async function searchPlayersAcrossRegions( region: 'com' as Region, })), ), - fetchBlitz( - `https://api.wotblitz.eu/wotb/account/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${encodedSearch}&limit=${normalizedLimit}`, - ).then( + fetchBlitz('eu', 'account/list', { + search, + limit: normalizedLimit, + }).then( (value) => value && value.map((account) => ({ @@ -43,9 +43,10 @@ export default async function searchPlayersAcrossRegions( region: 'eu' as Region, })), ), - fetchBlitz( - `https://api.wotblitz.asia/wotb/account/list/?application_id=${WARGAMING_APPLICATION_ID}&search=${encodedSearch}&limit=${normalizedLimit}`, - ).then( + fetchBlitz('asia', 'account/list', { + search, + limit: normalizedLimit, + }).then( (value) => value && value.map((account) => ({ diff --git a/src/core/blitzkrieg/setSession.ts b/src/core/blitzkrieg/setSession.ts index fea967a3d..17a971fb3 100644 --- a/src/core/blitzkrieg/setSession.ts +++ b/src/core/blitzkrieg/setSession.ts @@ -1,5 +1,4 @@ import { Region } from '../../constants/regions'; -import { WARGAMING_APPLICATION_ID } from '../../constants/wargamingApplicationID'; import { useSession } from '../../stores/session'; import { NormalizedTankStats, TanksStats } from '../../types/tanksStats'; import fetchBlitz from '../blitz/fetchBlitz'; @@ -7,11 +6,9 @@ import fetchBlitz from '../blitz/fetchBlitz'; export async function setSession(region: Region, id: number, nickname: string) { // TODO: generalize this function and also check for more of these kind const rawTankStats = ( - await fetchBlitz( - `https://api.wotblitz.${region}/wotb/tanks/stats/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${id}`, - ) + await fetchBlitz(region, 'tanks/stats', { account_id: id }) )[id]; - const tankStats = rawTankStats.reduce( + const tankStats = rawTankStats!.reduce( (accumulator, tank) => ({ ...accumulator, [tank.tank_id]: tank,