feat(web): add API hooks and mappers

This commit is contained in:
dahyeon committed 2026-04-14 22:09:00 +09:00
1 parent 87447a4f09
commit 041b1fc8b9
5 files changed
+2337

No files matched your search

+762
View File
@@ -0,0 +1,762 @@
import { InteractionStatus } from '@azure/msal-browser';
import { useMsal } from '@azure/msal-react';
import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
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 type {
ApiAuction,
ApiAuctionHistoryEntry,
ApiChampionStatsResponse,
ApiCommunity,
ApiEnqueueRefreshResult,
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
ApiLeaderboardResponse,
LegacyImportJobsResponse,
LegacyImportMembersResponse,
LegacyMatchListResponse,
ApiMatch,
ApiRecentMatchesResponse,
ApiRecentSummaryResponse,
ApiTeamInsightsResponse,
ApiTournamentCode,
ApiUserInternalHistoryResponse,
ApiUserHistoryProfile,
DdragonManifest,
StartLegacyImportRequest,
StartLegacyImportResponse,
MatchStatus,
MatchMutationRequest,
MatchesResponse,
ManualTournamentResultCollectResponse,
MeResponse,
RiotQueueGroup,
RiotRankFilter,
RebuildLegacyMatchesResponse,
TournamentCodeBulkUploadResponse,
TournamentCodeListResponse,
TournamentCodeState,
TournamentCodeStatsResponse,
TournamentCodeUploadItem,
} from './types';
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
interface MatchesQueryOptions {
status?: MatchStatus;
limit?: number;
}
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));
const queryString = searchParams.toString();
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`;
}
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,
) {
return useQuery({
queryKey: ['matches', communityId, options.status ?? null, options.limit ?? null],
queryFn: async () => {
const response = await apiFetch<MatchesResponse>(
createMatchesPath(communityId, options),
{ auth: 'none' },
);
return response.matches;
},
enabled: Boolean(communityId),
});
}
export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({
queryKey: ['match', communityId, matchId ?? null],
queryFn: () =>
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, {
auth: 'none',
}),
enabled: Boolean(communityId && matchId),
retry: false,
});
}
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: ({
matchId,
sequence,
}: {
matchId: string;
sequence: number;
}) =>
apiFetch<ApiAuction>(
`/communities/${communityId}/matches/${matchId}/auction/undo`,
{
method: 'POST',
body: JSON.stringify({ sequence }),
},
),
});
}
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (body: MatchMutationRequest) =>
apiFetch<ApiMatch>(`/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<ApiMatch>(`/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,
) {
return useQuery({
queryKey: ['user-history-profile', communityId, userId ?? null],
queryFn: () =>
apiFetch<ApiUserHistoryProfile>(
`/communities/${communityId}/users/${userId}/history-profile`,
{ auth: 'none' },
),
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 authUserId = useAuthUserId();
const { accounts, inProgress, instance } = useMsal();
const account = isMsalConfigured
? (instance.getActiveAccount() ?? accounts[0] ?? null)
: null;
const accountKey = account?.homeAccountId ?? null;
const isMsalReady =
!isMsalConfigured || inProgress === InteractionStatus.None;
return useQuery({
queryKey: ['me', authUserId, accountKey],
queryFn: async () => {
if (!account) {
return apiFetch<MeResponse>('/me');
}
const response = await instance.acquireTokenSilent({
account,
scopes: [MSAL_API_SCOPE],
redirectUri: MSAL_SILENT_REDIRECT_URI,
});
return apiFetch<MeResponse>('/me', {
headers: {
Authorization: `Bearer ${response.accessToken}`,
},
});
},
enabled: Boolean(authUserId || isMsalReady),
retry: false,
});
}