49 lines
1.7 KiB
TypeScript
49 lines
1.7 KiB
TypeScript
import { useInject } from '@/lib/di/hooks/useInject';
|
|
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';
|
|
import { LEAGUE_SERVICE_TOKEN } from '@/lib/di/tokens';
|
|
import { DateFormatter } from '@/lib/formatters/DateFormatter';
|
|
import type { RaceDTO } from '@/lib/types/generated/RaceDTO';
|
|
import { LeagueScheduleRaceViewModel, LeagueScheduleViewModel } from '@/lib/view-models/LeagueScheduleViewModel';
|
|
import { useQuery } from '@tanstack/react-query';
|
|
|
|
function mapRaceDtoToViewModel(race: RaceDTO): LeagueScheduleRaceViewModel {
|
|
const scheduledAt = race.date ? new Date(race.date) : new Date(0);
|
|
const now = new Date();
|
|
const isPast = scheduledAt.getTime() < now.getTime();
|
|
|
|
return {
|
|
id: race.id,
|
|
name: race.name,
|
|
scheduledAt,
|
|
formattedDate: DateFormatter.formatShort(scheduledAt),
|
|
formattedTime: DateFormatter.formatTime(scheduledAt),
|
|
isPast,
|
|
isUpcoming: !isPast,
|
|
status: isPast ? 'completed' : 'scheduled',
|
|
track: undefined,
|
|
car: undefined,
|
|
sessionType: undefined,
|
|
isRegistered: undefined,
|
|
};
|
|
}
|
|
|
|
export function useLeagueSchedule(leagueId: string) {
|
|
const leagueService = useInject(LEAGUE_SERVICE_TOKEN);
|
|
|
|
const queryResult = useQuery({
|
|
queryKey: ['leagueSchedule', leagueId],
|
|
queryFn: async (): Promise<LeagueScheduleViewModel> => {
|
|
const result = await leagueService.getLeagueSchedule(leagueId);
|
|
if (result.isErr()) {
|
|
throw new Error(result.getError().message);
|
|
}
|
|
const dto = result.unwrap();
|
|
const races = dto.races.map(mapRaceDtoToViewModel);
|
|
return new LeagueScheduleViewModel(races);
|
|
},
|
|
enabled: !!leagueId,
|
|
});
|
|
|
|
return enhanceQueryResult(queryResult);
|
|
}
|