|
| 1 | +import { type LoaderFunctionArgs } from "react-router"; |
| 2 | +import { DapperTs } from "@thunderstore/dapper-ts"; |
| 3 | +import { |
| 4 | + getPublicEnvVariables, |
| 5 | + getSessionTools, |
| 6 | +} from "cyberstorm/security/publicEnvVariables"; |
| 7 | +import { ApiError, type GenericApiError } from "@thunderstore/thunderstore-api"; |
| 8 | +import { throwUserFacingPayloadResponse } from "cyberstorm/utils/errors/userFacingErrorResponse"; |
| 9 | + |
| 10 | +export function getLoaderTools() { |
| 11 | + let dapper: DapperTs; |
| 12 | + let sessionTools: ReturnType<typeof getSessionTools> | undefined; |
| 13 | + if (import.meta.env.SSR) { |
| 14 | + const publicEnvVariables = getPublicEnvVariables(["VITE_API_URL"]); |
| 15 | + dapper = new DapperTs(() => { |
| 16 | + return { |
| 17 | + apiHost: publicEnvVariables.VITE_API_URL, |
| 18 | + sessionId: undefined, |
| 19 | + }; |
| 20 | + }); |
| 21 | + } else { |
| 22 | + sessionTools = getSessionTools(); |
| 23 | + const sessionConfig = sessionTools?.getConfig(); |
| 24 | + dapper = new DapperTs(() => { |
| 25 | + return { |
| 26 | + apiHost: sessionConfig?.apiHost, |
| 27 | + sessionId: sessionConfig?.sessionId, |
| 28 | + }; |
| 29 | + }); |
| 30 | + } |
| 31 | + return { dapper, sessionTools }; |
| 32 | +} |
| 33 | + |
| 34 | +export function makeTeamSettingsTabLoader<T>( |
| 35 | + dataFetcher: (dapper: DapperTs, teamName: string) => Promise<T> |
| 36 | +) { |
| 37 | + return async function clientLoader({ params }: LoaderFunctionArgs) { |
| 38 | + const teamName = params.namespaceId; |
| 39 | + if (!teamName) { |
| 40 | + throwUserFacingPayloadResponse({ |
| 41 | + headline: "Team not found.", |
| 42 | + description: "We could not find the requested team.", |
| 43 | + category: "not_found", |
| 44 | + status: 404, |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + try { |
| 49 | + const { dapper } = getLoaderTools(); |
| 50 | + const data = await dataFetcher(dapper, teamName); |
| 51 | + return { teamName, ...data }; |
| 52 | + } catch (error) { |
| 53 | + if (error instanceof ApiError) { |
| 54 | + const status = error.response.status; |
| 55 | + const statusText = |
| 56 | + (error.responseJson as GenericApiError)?.detail ?? |
| 57 | + error.response.statusText; |
| 58 | + throw new Response(statusText, { status, statusText }); |
| 59 | + } |
| 60 | + throw error; |
| 61 | + } |
| 62 | + }; |
| 63 | +} |
0 commit comments