From b88e5816a93927d35b499d5fbb8e8fc47fb4bb9d Mon Sep 17 00:00:00 2001 From: Robert van Hoesel Date: Fri, 9 Feb 2024 03:28:48 +0100 Subject: [PATCH] Cleaner fix --- src/pages/players/[id]-[username].astro | 31 +++++++++++++++---------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/pages/players/[id]-[username].astro b/src/pages/players/[id]-[username].astro index 7d5fc58..3e7c7a5 100644 --- a/src/pages/players/[id]-[username].astro +++ b/src/pages/players/[id]-[username].astro @@ -6,7 +6,7 @@ import { Image } from "astro:assets" import infernals from "../../assets/game/factions/infernals-small.png" import vanguard from "../../assets/game/factions/vanguard-small.png" import MatchPreview from "../../components/widgets/MatchPreview.astro" -import { PlayersApi, type PlayerActivityStats } from "../../lib/api" +import { PlayersApi, type PlayerActivityStats, type PlayerResponse, type PlayerMatchesResponse } from "../../lib/api" import { RankedBadge } from "../../components/ui/RankedBadge" import PlayerActivity from "../../components/widgets/PlayerActivity.astro" const themes = { @@ -25,23 +25,30 @@ const themes = { } as const type Theme = keyof typeof themes -const playerId = Astro.params.id! - -const playerRequest = PlayersApi.getPlayer({ playerId }) -const playerMatchesRequest = PlayersApi.getPlayerMatches({ playerId }) -const playerActivityRequest = PlayersApi.getPlayerStatisticsActivity({ playerId }).catch(() => {}) +// to be moved to own file +async function getDataOrErrorResponse(...values: T): Promise<[{ -readonly [P in keyof T]: Awaited; }, error: Response | null]> { + try { + const result = await Promise.all(values) + return [result, null] + } catch (e) { + return [[] as any, new Response(null, { status: 500, statusText: `${e}`})] + } +} -const player = await playerRequest -const playerMatches = await playerMatchesRequest -const playerActivity = await playerActivityRequest +const playerId = Astro.params.id! +const [[player, playerMatches, playerActivity], error] = await getDataOrErrorResponse( + PlayersApi.getPlayer({ playerId }), + PlayersApi.getPlayerMatches({ playerId }), + PlayersApi.getPlayerStatisticsActivity({ playerId }), +) +if(error) return error; -const highestLeague = player.leaderboard_entries.reduce( +const highestLeague = player?.leaderboard_entries?.reduce( (acc, entry) => (entry.points > acc.points ? entry : acc), player.leaderboard_entries[0] ) --- - - +