Files
lolympus-tournament-support/apps/web/src/api/hooks.ts
T

1104 lines
30 KiB
TypeScript

import { InteractionStatus } from '@azure/msal-browser';
import { useMsal } from '@azure/msal-react';
import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
import type {
CompetitionCommandResponse,
CompetitionDetailResponse,
CreateSeriesAdjudicationRequest,
MatchDetailResponse,
MatchLifecycleStatus,
MatchListResponse,
ReverseSeriesResultRequest,
SeriesId,
SeriesReversalPreviewRequest,
SeriesReversalPreviewResponse,
TeamCompetitionViewResponse,
} from '@lolympus/contracts';
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
import { apiFetch } from '../lib/api';
import {
isMsalConfigured,
MSAL_API_SCOPE,
MSAL_SILENT_REDIRECT_URI,
} from '../lib/auth/msal.config';
import {
executeAuthScopedQuery,
resolveAuthQueryScope,
} from './auth-query-scope';
import type {
ApiAuction,
ApiAuctionHistoryEntry,
ApiChampionStatsResponse,
ApiCommunity,
ApiCommunityUserSearchCandidate,
ApiEnqueueRefreshResult,
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
ApiLeaderboardResponse,
LegacyImportJobsResponse,
LegacyImportMembersResponse,
LegacyMatchListResponse,
ApiRecentMatchesResponse,
ApiRecentSummaryResponse,
ApiTeamInsightsResponse,
ApiTournamentCode,
ApiUserInternalHistoryResponse,
ApiUserHistoryProfile,
DdragonManifest,
StartLegacyImportRequest,
StartLegacyImportResponse,
MatchMutationRequest,
ManualTournamentResultCollectResponse,
MeResponse,
RiotQueueGroup,
RiotRankFilter,
RebuildLegacyMatchesResponse,
TournamentCodeBulkUploadResponse,
TournamentCodeListResponse,
TournamentCodeState,
TournamentCodeStatsResponse,
TournamentCodeUploadItem,
} from './types';
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
interface MatchesQueryOptions {
status?: MatchLifecycleStatus;
limit?: number;
page?: number;
offset?: number;
scheduledFrom?: string;
scheduledTo?: string;
sort?: 'asc' | 'desc';
}
export interface UserHistoryFilters {
queueGroup?: RiotQueueGroup;
rank?: RiotRankFilter;
seasonId?: string;
championId?: number;
}
export interface CommunityInternalStatsFilters {
seasonId?: string;
from?: string;
to?: string;
championId?: number;
limit?: number;
}
function createMatchesPath(
communityId: string,
options: MatchesQueryOptions = {},
) {
const searchParams = new URLSearchParams();
if (options.status) searchParams.set('status', options.status);
if (options.limit) searchParams.set('limit', String(options.limit));
if (options.page) searchParams.set('page', String(options.page));
if (options.offset) searchParams.set('offset', String(options.offset));
if (options.scheduledFrom)
searchParams.set('scheduledFrom', options.scheduledFrom);
if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo);
if (options.sort) searchParams.set('sort', options.sort);
const queryString = searchParams.toString();
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`;
}
function useOptionalAuthQueryScope() {
const authUserId = useAuthUserId();
const { accounts, inProgress, instance } = useMsal();
const account = isMsalConfigured
? (instance.getActiveAccount() ?? accounts[0] ?? null)
: null;
const scope = resolveAuthQueryScope({
authUserId,
accountKey: account?.homeAccountId ?? null,
msalConfigured: isMsalConfigured,
msalReady: inProgress === InteractionStatus.None,
});
const fetch = <T>(path: string) =>
executeAuthScopedQuery({
accountKey: account?.homeAccountId ?? null,
acquireAccessToken: async () => {
if (!account) {
throw new Error('MSAL account is unavailable.');
}
const response = await instance.acquireTokenSilent({
account,
scopes: [MSAL_API_SCOPE],
redirectUri: MSAL_SILENT_REDIRECT_URI,
});
return response.accessToken;
},
request: (authorizationHeader) =>
apiFetch<T>(
path,
authorizationHeader
? { headers: { Authorization: authorizationHeader } }
: undefined,
),
});
return { ...scope, fetch };
}
export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({
queryKey: ['community', communityId],
queryFn: () =>
apiFetch<ApiCommunity>(`/communities/${communityId}`, { auth: 'none' }),
enabled: Boolean(communityId),
});
}
export function useMatches(
options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID,
) {
const authScope = useOptionalAuthQueryScope();
return useQuery({
queryKey: [
'matches',
communityId,
...authScope.cacheKey,
options.status ?? null,
options.limit ?? null,
options.page ?? null,
options.offset ?? null,
options.scheduledFrom ?? null,
options.scheduledTo ?? null,
options.sort ?? null,
],
queryFn: async () => {
const response = await authScope.fetch<MatchListResponse>(
createMatchesPath(communityId, options),
);
return response.matches;
},
enabled: Boolean(communityId && authScope.ready),
});
}
export function useMatchesPage(
options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID,
) {
const authScope = useOptionalAuthQueryScope();
return useQuery({
queryKey: [
'matches-page',
communityId,
...authScope.cacheKey,
options.status ?? null,
options.limit ?? null,
options.page ?? null,
options.offset ?? null,
options.scheduledFrom ?? null,
options.scheduledTo ?? null,
options.sort ?? null,
],
queryFn: () =>
authScope.fetch<MatchListResponse>(
createMatchesPath(communityId, options),
),
enabled: Boolean(communityId && authScope.ready),
placeholderData: (previousData) => previousData,
});
}
export function useMatch(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
) {
const authScope = useOptionalAuthQueryScope();
const queryKey = [
'match',
communityId,
matchId ?? null,
...authScope.cacheKey,
] as const;
const query = useQuery({
queryKey,
queryFn: () =>
authScope.fetch<MatchDetailResponse>(
`/communities/${communityId}/matches/${matchId}`,
),
enabled: Boolean(communityId && matchId && authScope.ready),
retry: false,
});
return { ...query, queryKey };
}
export function useCompetition(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['competition', communityId, matchId ?? null],
queryFn: () =>
apiFetch<CompetitionDetailResponse>(
`/communities/${communityId}/matches/${matchId}/competition`,
{
auth: 'none',
},
),
enabled: enabled && Boolean(communityId && matchId),
retry: false,
});
}
export function useTeamCompetition(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
teamId?: string,
) {
return useQuery({
queryKey: ['competition-team', communityId, matchId ?? null, teamId ?? null],
queryFn: () =>
apiFetch<TeamCompetitionViewResponse>(
`/communities/${communityId}/matches/${matchId}/competition/team${
teamId ? `?teamId=${encodeURIComponent(teamId)}` : ''
}`,
),
enabled: Boolean(communityId && matchId),
retry: false,
});
}
type CompetitionMutationScope = {
matchId: string;
seriesId: SeriesId;
revision: number;
};
type IdempotentCompetitionMutationScope = CompetitionMutationScope & {
idempotencyKey: string;
};
function competitionCommandHeaders(revision: number, idempotencyKey?: string) {
return {
'If-Match': `"${revision}"`,
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
};
}
export function useAdjudicateCompetitionSeries(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (
params: IdempotentCompetitionMutationScope & {
request: CreateSeriesAdjudicationRequest;
},
) =>
apiFetch<CompetitionCommandResponse>(
`/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/adjudications`,
{
method: 'POST',
headers: competitionCommandHeaders(
params.revision,
params.idempotencyKey,
),
body: JSON.stringify(params.request),
},
),
retry: false,
});
}
export function usePreviewCompetitionSeriesReversal(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (
params: CompetitionMutationScope & {
request: SeriesReversalPreviewRequest;
},
) =>
apiFetch<SeriesReversalPreviewResponse>(
`/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/reversal-preview`,
{
method: 'POST',
headers: competitionCommandHeaders(params.revision),
body: JSON.stringify(params.request),
},
),
retry: false,
});
}
export function useReverseCompetitionSeries(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (
params: IdempotentCompetitionMutationScope & {
request: ReverseSeriesResultRequest;
},
) =>
apiFetch<CompetitionCommandResponse>(
`/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/reverse`,
{
method: 'POST',
headers: competitionCommandHeaders(
params.revision,
params.idempotencyKey,
),
body: JSON.stringify(params.request),
},
),
retry: false,
});
}
export function useCommunityUserSearch(
query: string,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['community-user-search', communityId, query],
queryFn: () => {
const searchParams = new URLSearchParams();
searchParams.set('query', query);
searchParams.set('limit', '10');
return apiFetch<ApiCommunityUserSearchCandidate[]>(
`/communities/${communityId}/users/search?${searchParams.toString()}`,
);
},
enabled: Boolean(communityId && enabled && query.trim().length >= 2),
});
}
export function useAuction(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
options: { refetchInterval?: number | false } = {},
) {
return useQuery({
queryKey: ['auction', communityId, matchId ?? null],
queryFn: () =>
apiFetch<ApiAuction>(
`/communities/${communityId}/matches/${matchId}/auction`,
{ auth: 'none' },
),
enabled: Boolean(communityId && matchId),
retry: false,
refetchInterval: options.refetchInterval,
});
}
export function useAuctionHistory(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
options: { enabled?: boolean; refetchInterval?: number | false } = {},
) {
return useQuery({
queryKey: ['auction-history', communityId, matchId ?? null],
queryFn: () =>
apiFetch<ApiAuctionHistoryEntry[]>(
`/communities/${communityId}/matches/${matchId}/auction/history`,
),
enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
retry: false,
refetchInterval: options.refetchInterval,
});
}
export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
matchId,
sequence,
}: {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
matchId: string;
sequence: number;
}) =>
apiFetch<ApiAuction>(
`/communities/${communityId}/matches/${matchId}/auction/undo`,
{
method: 'POST',
body: JSON.stringify({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
sequence,
}),
},
),
});
}
export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
matchId,
}: {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
matchId: string;
}) =>
apiFetch<void>(`/communities/${communityId}/matches/${matchId}/auction`, {
method: 'DELETE',
body: JSON.stringify({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
}),
}),
});
}
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (body: MatchMutationRequest) =>
apiFetch<MatchDetailResponse>(`/communities/${communityId}/matches`, {
method: 'POST',
body: JSON.stringify(body),
}),
});
}
export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({
matchId,
body,
}: {
matchId: string;
body: Partial<MatchMutationRequest>;
}) =>
apiFetch<MatchDetailResponse>(
`/communities/${communityId}/matches/${matchId}`,
{
method: 'PATCH',
body: JSON.stringify(body),
},
),
});
}
function createUserHistoryPath(
communityId: string,
userId: string,
resource: string,
filters: UserHistoryFilters = {},
extra: Record<string, string | number | null | undefined> = {},
) {
const searchParams = new URLSearchParams();
if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup);
if (filters.rank) searchParams.set('rank', filters.rank);
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
if (filters.championId)
searchParams.set('championId', String(filters.championId));
for (const [key, value] of Object.entries(extra)) {
if (value !== null && value !== undefined && value !== '') {
searchParams.set(key, String(value));
}
}
const queryString = searchParams.toString();
return `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`;
}
export function useUserHistoryProfile(
userId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['user-history-profile', communityId, userId ?? null],
queryFn: () =>
apiFetch<ApiUserHistoryProfile>(
`/communities/${communityId}/users/${userId}/history-profile`,
{ auth: 'none' },
),
enabled: enabled && Boolean(communityId && userId),
retry: false,
});
}
export function useChampionStats(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'user-champion-stats',
communityId,
userId ?? null,
filters.queueGroup ?? null,
filters.rank ?? null,
filters.seasonId ?? null,
],
queryFn: () =>
apiFetch<ApiChampionStatsResponse>(
createUserHistoryPath(
communityId,
userId ?? '',
'champion-stats',
filters,
),
{
auth: 'none',
},
),
enabled: Boolean(communityId && userId && enabled),
});
}
export function useRecentSummary(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'user-recent-summary',
communityId,
userId ?? null,
filters.queueGroup ?? null,
filters.rank ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
],
queryFn: () =>
apiFetch<ApiRecentSummaryResponse>(
createUserHistoryPath(
communityId,
userId ?? '',
'recent-summary',
filters,
),
{
auth: 'none',
},
),
enabled: Boolean(communityId && userId && enabled),
});
}
export function useRecentMatches(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: [
'user-recent-matches',
communityId,
userId ?? null,
filters.queueGroup ?? null,
filters.rank ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiRecentMatchesResponse>(
createUserHistoryPath(
communityId,
userId ?? '',
'recent-matches',
filters,
{
cursor: pageParam,
limit: 10,
},
),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && userId && enabled),
});
}
function createCommunityInternalStatsPath(
communityId: string,
resource: string,
filters: CommunityInternalStatsFilters = {},
extra: Record<string, string | number | null | undefined> = {},
) {
const searchParams = new URLSearchParams();
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
if (filters.from) searchParams.set('from', filters.from);
if (filters.to) searchParams.set('to', filters.to);
if (filters.championId)
searchParams.set('championId', String(filters.championId));
if (filters.limit) searchParams.set('limit', String(filters.limit));
for (const [key, value] of Object.entries(extra)) {
if (value !== null && value !== undefined && value !== '') {
searchParams.set(key, String(value));
}
}
const queryString = searchParams.toString();
return `/communities/${communityId}/internal-stats/${resource}${queryString ? `?${queryString}` : ''}`;
}
export function useCommunityInternalStatsMatches(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: [
'community-internal-stats-matches',
communityId,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
filters.limit ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiInternalMatchListResponse>(
createCommunityInternalStatsPath(communityId, 'matches', filters, {
cursor: pageParam,
}),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && enabled),
});
}
export function useCommunityLeaderboard(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'community-internal-stats-leaderboard',
communityId,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
],
queryFn: () =>
apiFetch<ApiLeaderboardResponse>(
createCommunityInternalStatsPath(communityId, 'leaderboard', filters),
{
auth: 'none',
},
),
enabled: Boolean(communityId && enabled),
});
}
export function useTeamInsights(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'community-internal-stats-team-insights',
communityId,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
],
queryFn: () =>
apiFetch<ApiTeamInsightsResponse>(
createCommunityInternalStatsPath(communityId, 'team-insights', filters),
{
auth: 'none',
},
),
enabled: Boolean(communityId && enabled),
});
}
export function useInternalMatchDetail(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useQuery({
queryKey: ['community-internal-stats-match', communityId, matchId ?? null],
queryFn: () =>
apiFetch<ApiInternalMatchDetailResponse>(
`/communities/${communityId}/internal-stats/match/${matchId}`,
{
auth: 'none',
},
),
enabled: Boolean(communityId && matchId),
retry: false,
});
}
export function useUserInternalHistory(
userId: string | undefined,
filters: UserHistoryFilters,
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: [
'user-internal-history',
communityId,
userId ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiUserInternalHistoryResponse>(
createUserHistoryPath(
communityId,
userId ?? '',
'internal-history',
filters,
{
cursor: pageParam,
limit: 10,
},
),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && userId && enabled),
});
}
export function useRefreshUserHistory(
userId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (body: {
queueGroups: RiotQueueGroup[];
priority: 'high' | 'low';
}) =>
apiFetch<ApiEnqueueRefreshResult>(
`/communities/${communityId}/users/${userId}/refresh`,
{
method: 'POST',
body: JSON.stringify(body),
},
),
});
}
export function useDdragonManifest(locale = 'ko_KR') {
return useQuery({
queryKey: ['ddragon-manifest', locale],
queryFn: () =>
apiFetch<DdragonManifest>(
`/riot/ddragon/manifest?locale=${encodeURIComponent(locale)}`,
{ auth: 'none' },
),
staleTime: DDRAGON_MANIFEST_STALE_MS,
gcTime: DDRAGON_MANIFEST_STALE_MS,
refetchOnMount: false,
refetchOnReconnect: false,
});
}
export function useTournamentCodeStats(
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['tournament-code-stats', communityId],
queryFn: () =>
apiFetch<TournamentCodeStatsResponse>(
`/communities/${communityId}/tournament-codes/stats`,
),
enabled: Boolean(communityId && enabled),
refetchInterval: enabled ? 30_000 : false,
retry: false,
});
}
export function useTournamentCodes(
options: { state?: TournamentCodeState; limit?: number },
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'tournament-codes',
communityId,
options.state ?? null,
options.limit ?? null,
],
queryFn: () => {
const searchParams = new URLSearchParams();
if (options.state) searchParams.set('state', options.state);
if (options.limit) searchParams.set('limit', String(options.limit));
const queryString = searchParams.toString();
return apiFetch<TournamentCodeListResponse>(
`/communities/${communityId}/tournament-codes${queryString ? `?${queryString}` : ''}`,
);
},
enabled: Boolean(communityId && enabled),
refetchInterval: enabled ? 30_000 : false,
retry: false,
});
}
export function useBulkUploadTournamentCodes(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (codes: TournamentCodeUploadItem[]) =>
apiFetch<TournamentCodeBulkUploadResponse>(
`/communities/${communityId}/tournament-codes`,
{
method: 'POST',
body: JSON.stringify({ codes }),
},
),
});
}
export function useRestoreTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (codeId: string) =>
apiFetch<ApiTournamentCode>(
`/communities/${communityId}/tournament-codes/${codeId}/release`,
{ method: 'POST' },
),
});
}
export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (codeId: string) =>
apiFetch<void>(`/communities/${communityId}/tournament-codes/${codeId}`, {
method: 'DELETE',
}),
});
}
export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (matchId: string) =>
apiFetch<{
jobId: string;
matchId: string;
priority: 'high' | 'low';
attempt: number;
expandedToAllPuuids: boolean;
}>(
`/communities/${communityId}/matches/${matchId}/poll-tournament-result`,
{
method: 'POST',
},
),
});
}
export function useCollectTournamentResultByWindow(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (params: {
matchId: string;
startTime: string;
endTime: string;
}) =>
apiFetch<ManualTournamentResultCollectResponse>(
`/communities/${communityId}/matches/${params.matchId}/poll-tournament-result/collect-by-window`,
{
method: 'POST',
body: JSON.stringify({
startTime: params.startTime,
endTime: params.endTime,
}),
},
),
});
}
export function useCollectTournamentResultByRiotMatch(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (params: { matchId: string; riotMatchId: string }) =>
apiFetch<ManualTournamentResultCollectResponse>(
`/communities/${communityId}/matches/${params.matchId}/poll-tournament-result/collect-by-riot-match`,
{
method: 'POST',
body: JSON.stringify({ riotMatchId: params.riotMatchId }),
},
),
});
}
export function useLegacyImportMembers(
options: { windowStart?: string; windowEnd?: string },
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'legacy-import-members',
communityId,
options.windowStart ?? null,
options.windowEnd ?? null,
],
queryFn: () => {
const searchParams = new URLSearchParams();
if (options.windowStart)
searchParams.set('windowStart', options.windowStart);
if (options.windowEnd) searchParams.set('windowEnd', options.windowEnd);
const queryString = searchParams.toString();
return apiFetch<LegacyImportMembersResponse>(
`/communities/${communityId}/legacy-import/members${queryString ? `?${queryString}` : ''}`,
);
},
enabled: Boolean(communityId && enabled),
});
}
export function useLegacyImportJobs(
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['legacy-import-jobs', communityId],
queryFn: () =>
apiFetch<LegacyImportJobsResponse>(
`/communities/${communityId}/legacy-import-jobs?limit=10`,
),
enabled: Boolean(communityId && enabled),
refetchInterval: (query) =>
query.state.data?.jobs.some(
(job) => job.state === 'pending' || job.state === 'running',
)
? 5_000
: false,
});
}
export function useStartLegacyImport(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (body: StartLegacyImportRequest) =>
apiFetch<StartLegacyImportResponse>(
`/communities/${communityId}/legacy-import`,
{
method: 'POST',
body: JSON.stringify(body),
},
),
});
}
export function useCancelLegacyImport(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (jobId: string) =>
apiFetch<void>(
`/communities/${communityId}/legacy-import-jobs/${jobId}/cancel`,
{ method: 'POST' },
),
});
}
export function useLegacyMatches(
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: ['legacy-matches', communityId],
queryFn: ({ pageParam }) => {
const searchParams = new URLSearchParams({ limit: '50' });
if (pageParam) searchParams.set('cursor', String(pageParam));
return apiFetch<LegacyMatchListResponse>(
`/communities/${communityId}/legacy-matches?${searchParams.toString()}`,
);
},
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && enabled),
});
}
export function useDeleteMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (matchId: string) =>
apiFetch<void>(`/communities/${communityId}/matches/${matchId}`, {
method: 'DELETE',
}),
});
}
export function useBulkDeleteLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (matchIds: string[]) =>
apiFetch<{ deleted: number }>(
`/communities/${communityId}/legacy-matches/bulk-delete`,
{
method: 'POST',
body: JSON.stringify({ matchIds }),
},
),
});
}
export function useRebuildLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: () =>
apiFetch<RebuildLegacyMatchesResponse>(
`/communities/${communityId}/legacy-matches/rebuild`,
{ method: 'POST' },
),
});
}
export function useMe() {
const authScope = useOptionalAuthQueryScope();
return useQuery({
queryKey: ['me', ...authScope.cacheKey],
queryFn: () => authScope.fetch<MeResponse>('/me'),
enabled: authScope.ready,
retry: false,
});
}