feat(web): add auth config and API layer
This commit is contained in:
1 parent
f520187531
commit
65f12f2560
13 files changed
+2359
No files matched your search
@@ -0,0 +1,7 @@
|
||||
VITE_API_BASE_URL=http://localhost:3000
|
||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html
|
||||
@@ -0,0 +1,7 @@
|
||||
VITE_API_BASE_URL=http://localhost:3000
|
||||
VITE_DEFAULT_COMMUNITY_ID=
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/<tenant-id>
|
||||
VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html
|
||||
@@ -0,0 +1,8 @@
|
||||
VITE_API_BASE_URL=https://lolympus-api.dahyeon.us
|
||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback
|
||||
VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
VITE_API_BASE_URL=https://lolympus-test-api.dahyeon.us
|
||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
@@ -0,0 +1,664 @@
|
||||
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,
|
||||
ApiChampionStatsResponse,
|
||||
ApiCommunity,
|
||||
ApiEnqueueRefreshResult,
|
||||
ApiInternalMatchDetailResponse,
|
||||
ApiInternalMatchListResponse,
|
||||
ApiLeaderboardResponse,
|
||||
LegacyImportJobsResponse,
|
||||
LegacyImportMembersResponse,
|
||||
LegacyMatchListResponse,
|
||||
ApiMatch,
|
||||
ApiRecentMatchesResponse,
|
||||
ApiRecentSummaryResponse,
|
||||
ApiTeamInsightsResponse,
|
||||
ApiTournamentCode,
|
||||
ApiUserInternalHistoryResponse,
|
||||
ApiUserHistoryProfile,
|
||||
DdragonManifest,
|
||||
StartLegacyImportRequest,
|
||||
StartLegacyImportResponse,
|
||||
MatchStatus,
|
||||
MatchesResponse,
|
||||
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,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
apiFetch<ApiAuction>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction`,
|
||||
{ auth: 'none' },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
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 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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
import type {
|
||||
ApiAuction,
|
||||
ApiAuctionPlayerSnapshot,
|
||||
ApiAuctionTeam,
|
||||
ApiMatch,
|
||||
ApiMatchParticipant,
|
||||
ApiPositionPreference,
|
||||
ApiRiotLaneStats,
|
||||
ApiRiotRecentStatsSummary,
|
||||
ApiTierInfo,
|
||||
MatchStatus,
|
||||
Position,
|
||||
RiotLane,
|
||||
TeamSide,
|
||||
TournamentCodeSlotView,
|
||||
} from "./types";
|
||||
import { POSITION_ORDER, sideLabel } from "../lib/league";
|
||||
|
||||
export interface ParticipantView {
|
||||
id: string;
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
tag: string;
|
||||
tier?: ApiTierInfo;
|
||||
mainPosition: Position;
|
||||
subPosition: Position;
|
||||
profileIconId: number;
|
||||
}
|
||||
|
||||
export interface TeamParticipantView extends ParticipantView {
|
||||
assignedPosition: Position;
|
||||
cost?: number;
|
||||
}
|
||||
|
||||
export interface TeamView {
|
||||
side: TeamSide;
|
||||
name: string;
|
||||
participants: TeamParticipantView[];
|
||||
}
|
||||
|
||||
export interface MatchDetailView {
|
||||
id: string;
|
||||
title: string;
|
||||
date: string;
|
||||
time: string;
|
||||
status: MatchStatus;
|
||||
description: string;
|
||||
map: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
tournamentCodes: TournamentCodeSlotView[];
|
||||
joined: boolean;
|
||||
participants: ParticipantView[];
|
||||
teams: TeamView[];
|
||||
result?: {
|
||||
winner?: string;
|
||||
winnerSide?: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
riotMatchIds: string[];
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
winnerSide: TeamSide;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: Array<{
|
||||
userId: string;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
win: boolean;
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
schedule: { time: string; label: string }[];
|
||||
}
|
||||
|
||||
export interface AuctionPlayerView extends ParticipantView {
|
||||
masteries: {
|
||||
championId: number;
|
||||
level: number;
|
||||
points: number;
|
||||
}[];
|
||||
recentStats: {
|
||||
overall: ApiRiotLaneStats;
|
||||
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
|
||||
primary: ApiRiotLaneStats | null;
|
||||
primarySource: "lane" | "overall" | "none";
|
||||
};
|
||||
}
|
||||
|
||||
export interface AuctionTeamView {
|
||||
side: TeamSide;
|
||||
captainUserId: string;
|
||||
captainName: string;
|
||||
points: number;
|
||||
members: (AuctionPlayerView & {
|
||||
assignedPosition: Position;
|
||||
cost: number;
|
||||
})[];
|
||||
}
|
||||
|
||||
export interface AuctionStateView {
|
||||
matchId: string;
|
||||
phase: ApiAuction["phase"];
|
||||
teams: [AuctionTeamView, AuctionTeamView];
|
||||
currentPlayer: AuctionPlayerView | null;
|
||||
currentPlayerIndex: number;
|
||||
totalPlayers: number;
|
||||
auctionOrder: AuctionPlayerView[];
|
||||
bids: {
|
||||
side: TeamSide;
|
||||
amount: number;
|
||||
timestamp: string;
|
||||
}[];
|
||||
currentBid: number;
|
||||
currentBidder: TeamSide | null;
|
||||
timer: number;
|
||||
maxTimer: number;
|
||||
deadline?: string;
|
||||
}
|
||||
|
||||
const MAP_LABELS: Record<number, string> = {
|
||||
11: "소환사의 협곡",
|
||||
12: "칼바람 나락",
|
||||
21: "소환사의 협곡",
|
||||
22: "전략적 팀 전투",
|
||||
};
|
||||
|
||||
const TIER_NAMES: Record<string, string> = {
|
||||
IRON: "아이언",
|
||||
BRONZE: "브론즈",
|
||||
SILVER: "실버",
|
||||
GOLD: "골드",
|
||||
PLATINUM: "플래티넘",
|
||||
EMERALD: "에메랄드",
|
||||
DIAMOND: "다이아",
|
||||
MASTER: "마스터",
|
||||
GRANDMASTER: "그랜드마스터",
|
||||
CHALLENGER: "챌린저",
|
||||
};
|
||||
|
||||
const POSITION_TO_RIOT_LANE: Record<Position, RiotLane> = {
|
||||
TOP: "TOP",
|
||||
JGL: "JUNGLE",
|
||||
MID: "MIDDLE",
|
||||
ADC: "BOTTOM",
|
||||
SUP: "UTILITY",
|
||||
};
|
||||
|
||||
function createEmptyLaneStats(): ApiRiotLaneStats {
|
||||
return {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
avgKills: 0,
|
||||
avgDeaths: 0,
|
||||
avgAssists: 0,
|
||||
avgCs: 0,
|
||||
avgCsPerMin: 0,
|
||||
mostPlayedChampionIds: [],
|
||||
};
|
||||
}
|
||||
|
||||
function createEmptyRecentStatsView(): AuctionPlayerView["recentStats"] {
|
||||
return {
|
||||
overall: createEmptyLaneStats(),
|
||||
byLane: {},
|
||||
primary: null,
|
||||
primarySource: "none",
|
||||
};
|
||||
}
|
||||
|
||||
function sortPreferredPositions(preferredPositions: ApiPositionPreference[]) {
|
||||
return [...preferredPositions].sort(
|
||||
(left, right) => left.priority - right.priority,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveMainAndSubPosition(
|
||||
preferredPositions: ApiPositionPreference[],
|
||||
) {
|
||||
const sorted = sortPreferredPositions(preferredPositions);
|
||||
return {
|
||||
mainPosition: sorted[0]?.position ?? "MID",
|
||||
subPosition: sorted[1]?.position ?? sorted[0]?.position ?? "MID",
|
||||
};
|
||||
}
|
||||
|
||||
function mapMatchParticipantToView(
|
||||
participant: ApiMatchParticipant,
|
||||
): ParticipantView {
|
||||
const { mainPosition, subPosition } = resolveMainAndSubPosition(
|
||||
participant.preferredPositions,
|
||||
);
|
||||
|
||||
return {
|
||||
id: participant.userId,
|
||||
userId: participant.userId,
|
||||
summonerName: participant.gameName ?? "알 수 없음",
|
||||
tag: participant.tagLine ?? "----",
|
||||
tier: participant.tier,
|
||||
mainPosition,
|
||||
subPosition,
|
||||
profileIconId: participant.profileIconId ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
function mapAuctionPlayerToView(
|
||||
player: ApiAuctionPlayerSnapshot,
|
||||
): AuctionPlayerView {
|
||||
const { mainPosition, subPosition } = resolveMainAndSubPosition(
|
||||
player.preferredPositions,
|
||||
);
|
||||
const summary = player.recentStatsSummary;
|
||||
const primary = pickPrimary(summary, mainPosition);
|
||||
|
||||
return {
|
||||
id: player.userId,
|
||||
userId: player.userId,
|
||||
summonerName: player.gameName,
|
||||
tag: player.tagLine,
|
||||
tier: selectPrimaryTier(player.tiers),
|
||||
mainPosition,
|
||||
subPosition,
|
||||
profileIconId: player.profileIconId,
|
||||
masteries: player.masteries.slice(0, 5).map((mastery) => ({
|
||||
championId: mastery.championId,
|
||||
level: mastery.championLevel,
|
||||
points: mastery.championPoints,
|
||||
})),
|
||||
recentStats: {
|
||||
overall: summary?.overall ?? createEmptyLaneStats(),
|
||||
byLane: summary?.byLane ?? {},
|
||||
primary: primary.stats,
|
||||
primarySource: primary.source,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFallbackParticipant(userId: string): ParticipantView {
|
||||
return {
|
||||
id: userId,
|
||||
userId,
|
||||
summonerName: `User ${userId.slice(-4)}`,
|
||||
tag: "----",
|
||||
mainPosition: "MID",
|
||||
subPosition: "MID",
|
||||
profileIconId: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function mapAuctionTeamToView(
|
||||
team: ApiAuctionTeam,
|
||||
playerLookup: Map<string, AuctionPlayerView>,
|
||||
participantLookup: Map<string, ParticipantView>,
|
||||
): AuctionTeamView {
|
||||
return {
|
||||
side: team.side,
|
||||
captainUserId: team.captainUserId,
|
||||
captainName:
|
||||
participantLookup.get(team.captainUserId)?.summonerName ??
|
||||
`User ${team.captainUserId.slice(-4)}`,
|
||||
points: team.points,
|
||||
members: team.members.map((member) => {
|
||||
const participant = participantLookup.get(member.userId);
|
||||
const player =
|
||||
playerLookup.get(member.userId) ??
|
||||
(participant
|
||||
? {
|
||||
...participant,
|
||||
masteries: [],
|
||||
recentStats: createEmptyRecentStatsView(),
|
||||
}
|
||||
: {
|
||||
...createFallbackParticipant(member.userId),
|
||||
masteries: [],
|
||||
recentStats: createEmptyRecentStatsView(),
|
||||
});
|
||||
|
||||
return {
|
||||
...player,
|
||||
assignedPosition: member.assignedPosition,
|
||||
cost: member.cost,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function mapIdToLabel(mapId: number) {
|
||||
return MAP_LABELS[mapId] ?? `맵 #${mapId}`;
|
||||
}
|
||||
|
||||
export function formatKoreanDate(dateLike: string | Date) {
|
||||
const date = new Date(dateLike);
|
||||
|
||||
return {
|
||||
date: new Intl.DateTimeFormat("ko-KR", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
weekday: "short",
|
||||
}).format(date),
|
||||
time: new Intl.DateTimeFormat("ko-KR", {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}).format(date),
|
||||
};
|
||||
}
|
||||
|
||||
function pickPrimary(
|
||||
summary: ApiRiotRecentStatsSummary | undefined,
|
||||
mainPosition: Position,
|
||||
): {
|
||||
stats: ApiRiotLaneStats | null;
|
||||
source: "lane" | "overall" | "none";
|
||||
} {
|
||||
if (!summary) {
|
||||
return { stats: null, source: "none" };
|
||||
}
|
||||
|
||||
const laneStats = summary.byLane[POSITION_TO_RIOT_LANE[mainPosition]];
|
||||
if (laneStats && laneStats.games > 0) {
|
||||
return { stats: laneStats, source: "lane" };
|
||||
}
|
||||
|
||||
if (summary.overall.games > 0) {
|
||||
return { stats: summary.overall, source: "overall" };
|
||||
}
|
||||
|
||||
return { stats: null, source: "none" };
|
||||
}
|
||||
|
||||
export function selectPrimaryTier(tiers: ApiTierInfo[]) {
|
||||
return tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? tiers[0];
|
||||
}
|
||||
|
||||
export function formatTierLabel(tier?: ApiTierInfo) {
|
||||
if (!tier) return "미등록";
|
||||
|
||||
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
|
||||
const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier);
|
||||
|
||||
if (highTier && tier.leaguePoints > 0) {
|
||||
return `${tierName} ${tier.leaguePoints}LP`;
|
||||
}
|
||||
|
||||
return tier.rank ? `${tierName} ${tier.rank}` : tierName;
|
||||
}
|
||||
|
||||
export function getTierColorToken(tier?: ApiTierInfo) {
|
||||
switch (tier?.tier) {
|
||||
case "CHALLENGER":
|
||||
return "text-amber-400";
|
||||
case "GRANDMASTER":
|
||||
return "text-red-400";
|
||||
case "MASTER":
|
||||
return "text-fuchsia-400";
|
||||
case "DIAMOND":
|
||||
return "text-cyan-400";
|
||||
case "EMERALD":
|
||||
return "text-emerald-400";
|
||||
case "PLATINUM":
|
||||
return "text-teal-300";
|
||||
case "GOLD":
|
||||
return "text-yellow-400";
|
||||
case "SILVER":
|
||||
return "text-gray-300";
|
||||
case "BRONZE":
|
||||
return "text-amber-700";
|
||||
case "IRON":
|
||||
return "text-stone-400";
|
||||
default:
|
||||
return "text-base-content/50";
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDefaultPreferredPositions() {
|
||||
return POSITION_ORDER.map((position, index) => ({
|
||||
position,
|
||||
priority: index + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
const formattedDate = formatKoreanDate(match.scheduledAt);
|
||||
const participants = match.participants.map(mapMatchParticipantToView);
|
||||
const participantLookup = new Map(
|
||||
participants.map((participant) => [participant.userId, participant]),
|
||||
);
|
||||
|
||||
const teams = match.teams.map((team) => ({
|
||||
side: team.side,
|
||||
name: team.name || sideLabel(team.side),
|
||||
participants: team.members.map((member) => {
|
||||
const participant =
|
||||
participantLookup.get(member.userId) ??
|
||||
createFallbackParticipant(member.userId);
|
||||
|
||||
return {
|
||||
...participant,
|
||||
assignedPosition: member.assignedPosition,
|
||||
cost: member.cost,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
const winnerTeam = match.result?.winnerSide
|
||||
? teams.find((team) => team.side === match.result?.winnerSide)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: match._id,
|
||||
title: match.title,
|
||||
date: formattedDate.date,
|
||||
time: formattedDate.time,
|
||||
status: match.status,
|
||||
description: match.description,
|
||||
map: mapIdToLabel(match.mapId),
|
||||
maxParticipants: match.maxParticipants,
|
||||
gameCount: match.gameCount ?? 3,
|
||||
tournamentCodes: match.tournamentCodes ?? [],
|
||||
joined: Boolean(match.joined),
|
||||
participants,
|
||||
teams,
|
||||
result: match.result
|
||||
? {
|
||||
winner: match.result.winnerSide
|
||||
? winnerTeam?.name ?? sideLabel(match.result.winnerSide)
|
||||
: undefined,
|
||||
winnerSide: match.result.winnerSide,
|
||||
blueScore: match.result.blueScore,
|
||||
redScore: match.result.redScore,
|
||||
riotMatchIds: match.result.riotMatchIds,
|
||||
games: [...(match.result.games ?? [])].sort(
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
),
|
||||
}
|
||||
: undefined,
|
||||
prizes: match.prizes,
|
||||
notices: match.notices,
|
||||
schedule: match.schedule,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapApiAuctionToAuctionState(
|
||||
auction: ApiAuction,
|
||||
match: ApiMatch,
|
||||
now = new Date(),
|
||||
): AuctionStateView {
|
||||
const participantLookup = new Map(
|
||||
match.participants
|
||||
.map(mapMatchParticipantToView)
|
||||
.map((participant) => [participant.userId, participant]),
|
||||
);
|
||||
const auctionOrder = auction.order.map(mapAuctionPlayerToView);
|
||||
const auctionPlayerLookup = new Map(
|
||||
auctionOrder.map((player) => [player.userId, player]),
|
||||
);
|
||||
const blueTeam =
|
||||
auction.teams.find((team) => team.side === "blue") ??
|
||||
({
|
||||
side: "blue",
|
||||
captainUserId: "",
|
||||
points: 0,
|
||||
members: [],
|
||||
} satisfies ApiAuctionTeam);
|
||||
const redTeam =
|
||||
auction.teams.find((team) => team.side === "red") ??
|
||||
({
|
||||
side: "red",
|
||||
captainUserId: "",
|
||||
points: 0,
|
||||
members: [],
|
||||
} satisfies ApiAuctionTeam);
|
||||
|
||||
const totalPlayers = auctionOrder.length;
|
||||
const currentPlayer =
|
||||
auction.phase === "complete"
|
||||
? null
|
||||
: (auctionPlayerLookup.get(
|
||||
auction.order[auction.currentIndex]?.userId ?? "",
|
||||
) ?? null);
|
||||
const currentPlayerIndex =
|
||||
auction.phase === "complete" ? totalPlayers : auction.currentIndex;
|
||||
const timer = auction.currentDeadline
|
||||
? Math.max(
|
||||
0,
|
||||
Math.ceil(
|
||||
(new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000,
|
||||
),
|
||||
)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
matchId: auction.matchId,
|
||||
phase: auction.phase,
|
||||
teams: [
|
||||
mapAuctionTeamToView(blueTeam, auctionPlayerLookup, participantLookup),
|
||||
mapAuctionTeamToView(redTeam, auctionPlayerLookup, participantLookup),
|
||||
],
|
||||
currentPlayer,
|
||||
currentPlayerIndex,
|
||||
totalPlayers,
|
||||
auctionOrder,
|
||||
bids: auction.bids.map((bid) => ({
|
||||
side: bid.side,
|
||||
amount: bid.amount,
|
||||
timestamp: bid.timestamp,
|
||||
})),
|
||||
currentBid: auction.currentBid,
|
||||
currentBidder: auction.currentBidder ?? null,
|
||||
timer,
|
||||
maxTimer: auction.maxTimerSeconds,
|
||||
deadline: auction.currentDeadline,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,737 @@
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export type MatchStatus =
|
||||
| 'recruiting'
|
||||
| 'team-built'
|
||||
| 'in-progress'
|
||||
| 'finished';
|
||||
export type AuctionPhase =
|
||||
| 'waiting'
|
||||
| 'presenting'
|
||||
| 'bidding'
|
||||
| 'sold'
|
||||
| 'complete';
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
|
||||
export interface ApiPositionPreference {
|
||||
position: Position;
|
||||
priority: number;
|
||||
}
|
||||
|
||||
export interface ApiTierInfo {
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiChampionMasteryEntry {
|
||||
puuid?: string;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
championPoints: number;
|
||||
lastPlayTime?: number;
|
||||
championPointsSinceLastLevel?: number;
|
||||
championPointsUntilNextLevel?: number;
|
||||
markRequiredForNextLevel?: number;
|
||||
tokensEarned?: number;
|
||||
championSeasonMilestone?: number;
|
||||
milestoneGrades?: string[];
|
||||
nextSeasonMilestone?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ApiRiotLaneStats {
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
avgCs: number;
|
||||
avgCsPerMin: number;
|
||||
mostPlayedChampionIds: number[];
|
||||
}
|
||||
|
||||
export interface ApiRiotRecentStatsSummary {
|
||||
overall: ApiRiotLaneStats;
|
||||
byLane: Partial<Record<RiotLane, ApiRiotLaneStats>>;
|
||||
}
|
||||
|
||||
export interface ApiRiotAccount {
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
revisionDate: number;
|
||||
summonerLevel: number;
|
||||
isPrimary: boolean;
|
||||
tiers: ApiTierInfo[];
|
||||
tierHistory: unknown[];
|
||||
matchIds: string[];
|
||||
championMasteries: ApiChampionMasteryEntry[];
|
||||
championRecords: Record<string, Record<string, unknown>>;
|
||||
recentStatsSummary?: ApiRiotRecentStatsSummary;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiUser {
|
||||
_id: string;
|
||||
communityId: string;
|
||||
identityId?: string;
|
||||
role: CommunityRole;
|
||||
kakaoTalkId?: string;
|
||||
kakaoTalkNickname?: string;
|
||||
discordId?: string;
|
||||
discordNickname?: string;
|
||||
riotAccounts: ApiRiotAccount[];
|
||||
preferredPositions: ApiPositionPreference[];
|
||||
isActivated: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiCommunity {
|
||||
_id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
ownerUserId: string;
|
||||
matchGameCount?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type TournamentCodeState =
|
||||
| 'available'
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'expired'
|
||||
| 'released';
|
||||
|
||||
export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeSlotState;
|
||||
riotMatchId: string | null;
|
||||
}
|
||||
|
||||
export interface ApiMatchParticipant {
|
||||
userId: string;
|
||||
puuid?: string;
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
profileIconId?: number;
|
||||
tier?: ApiTierInfo;
|
||||
preferredPositions: ApiPositionPreference[];
|
||||
joinedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiMatchTeamMember {
|
||||
userId: string;
|
||||
assignedPosition: Position;
|
||||
cost?: number;
|
||||
}
|
||||
|
||||
export interface ApiMatchTeam {
|
||||
side: TeamSide;
|
||||
name: string;
|
||||
captainUserId?: string;
|
||||
members: ApiMatchTeamMember[];
|
||||
}
|
||||
|
||||
export interface ApiMatchGameResultParticipant {
|
||||
userId: string;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
win: boolean;
|
||||
}
|
||||
|
||||
export interface ApiMatchGameResult {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
winnerSide: TeamSide;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: ApiMatchGameResultParticipant[];
|
||||
}
|
||||
|
||||
export interface ApiMatchResult {
|
||||
winnerSide?: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
mvpUserId?: string;
|
||||
riotMatchIds: string[];
|
||||
games: ApiMatchGameResult[];
|
||||
}
|
||||
|
||||
export interface ApiMatchScheduleItem {
|
||||
time: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ApiMatch {
|
||||
_id: string;
|
||||
communityId: string;
|
||||
title: string;
|
||||
description: string;
|
||||
mapId: number;
|
||||
status: MatchStatus;
|
||||
scheduledAt: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
tournamentCodes?: TournamentCodeSlotView[];
|
||||
hostUserId?: string;
|
||||
participants: ApiMatchParticipant[];
|
||||
teams: ApiMatchTeam[];
|
||||
result?: ApiMatchResult;
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
schedule: ApiMatchScheduleItem[];
|
||||
joined?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiAuctionPlayerSnapshot {
|
||||
userId: string;
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
preferredPositions: ApiPositionPreference[];
|
||||
tiers: ApiTierInfo[];
|
||||
masteries: ApiChampionMasteryEntry[];
|
||||
recentStatsSummary?: ApiRiotRecentStatsSummary;
|
||||
}
|
||||
|
||||
export interface ApiAuctionTeamMember {
|
||||
userId: string;
|
||||
assignedPosition: Position;
|
||||
cost: number;
|
||||
}
|
||||
|
||||
export interface ApiAuctionTeam {
|
||||
side: TeamSide;
|
||||
captainUserId: string;
|
||||
points: number;
|
||||
members: ApiAuctionTeamMember[];
|
||||
}
|
||||
|
||||
export interface ApiAuctionBid {
|
||||
side: TeamSide;
|
||||
amount: number;
|
||||
bidderUserId: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface ApiAuction {
|
||||
_id: string;
|
||||
matchId: string;
|
||||
phase: AuctionPhase;
|
||||
teams: ApiAuctionTeam[];
|
||||
order: ApiAuctionPlayerSnapshot[];
|
||||
currentIndex: number;
|
||||
bids: ApiAuctionBid[];
|
||||
currentBid: number;
|
||||
currentBidder?: TeamSide;
|
||||
maxTimerSeconds: number;
|
||||
currentDeadline?: string;
|
||||
initialPoints: number;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiIdentity {
|
||||
id: string;
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export interface ApiMembership {
|
||||
user: ApiUser;
|
||||
community: ApiCommunity | null;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
identity: ApiIdentity | null;
|
||||
memberships: ApiMembership[];
|
||||
}
|
||||
|
||||
export interface MatchesResponse {
|
||||
matches: ApiMatch[];
|
||||
}
|
||||
|
||||
export interface DdragonChampionEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
locale: string;
|
||||
champions: Record<string, DdragonChampionEntry>;
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL';
|
||||
|
||||
export interface ApiTournamentCode {
|
||||
_id: string;
|
||||
code: string;
|
||||
region: string;
|
||||
mapType: 'SUMMONERS_RIFT';
|
||||
teamSize: number;
|
||||
spectatorType: TournamentSpectatorType;
|
||||
metadata?: Record<string, unknown>;
|
||||
expiresAt: string;
|
||||
state: TournamentCodeState;
|
||||
matchId?: string;
|
||||
gameNumber?: number;
|
||||
reservedAt?: string;
|
||||
usedAt?: string;
|
||||
releasedAt?: string;
|
||||
riotMatchId?: string;
|
||||
uploadedBy: string;
|
||||
uploadedAt: string;
|
||||
source?: string;
|
||||
notes?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface TournamentCodeStatsResponse {
|
||||
byState: Record<TournamentCodeState, number>;
|
||||
expiringSoon: number;
|
||||
available: number;
|
||||
}
|
||||
|
||||
export interface TournamentCodeListResponse {
|
||||
codes: ApiTournamentCode[];
|
||||
}
|
||||
|
||||
export interface TournamentCodeUploadItem {
|
||||
code: string;
|
||||
expiresAt: string;
|
||||
spectatorType?: TournamentSpectatorType;
|
||||
metadata?: Record<string, unknown>;
|
||||
source?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface TournamentCodeBulkUploadResponse {
|
||||
inserted: number;
|
||||
duplicates: string[];
|
||||
invalid: Array<{ code: string; reason: string }>;
|
||||
}
|
||||
|
||||
export type RiotQueueGroup =
|
||||
| 'all'
|
||||
| 'summoners-rift'
|
||||
| 'aram'
|
||||
| 'urf'
|
||||
| 'arena'
|
||||
| 'internal';
|
||||
export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal';
|
||||
|
||||
export interface ApiHistorySeason {
|
||||
id: string;
|
||||
label: string;
|
||||
startedAt: string | null;
|
||||
endedAt: string | null;
|
||||
}
|
||||
|
||||
export interface ApiUserHistoryProfile {
|
||||
userId: string;
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
summonerLevel: number;
|
||||
tiers: ApiTierInfo[];
|
||||
season: ApiHistorySeason;
|
||||
seasons: ApiHistorySeason[];
|
||||
lastFetchedAt: string | null;
|
||||
}
|
||||
|
||||
export interface ApiChampionStatsRow {
|
||||
championId: number;
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
winRate: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
kda: number;
|
||||
totalKills: number;
|
||||
totalDeaths: number;
|
||||
totalAssists: number;
|
||||
doubleKills: number;
|
||||
tripleKills: number;
|
||||
quadraKills: number;
|
||||
pentaKills: number;
|
||||
avgCs: number;
|
||||
avgCsPerMin: number;
|
||||
}
|
||||
|
||||
export interface ApiChampionStatsResponse {
|
||||
queueGroup: RiotQueueGroup;
|
||||
rank: RiotRankFilter;
|
||||
queueIds: number[];
|
||||
season: ApiHistorySeason;
|
||||
lastFetchedAt: string | null;
|
||||
champions: ApiChampionStatsRow[];
|
||||
totals: ApiChampionStatsRow;
|
||||
}
|
||||
|
||||
export interface ApiRecentSummaryResponse {
|
||||
windowSize: number;
|
||||
winRate: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
streak: { type: 'win' | 'loss'; count: number } | null;
|
||||
kda: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
bestRating: {
|
||||
rating: number | 'Perfect';
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
matchId: string;
|
||||
} | null;
|
||||
positionRates: Partial<Record<RiotLane, number>>;
|
||||
topChampions: Array<{
|
||||
championId: number;
|
||||
games: number;
|
||||
winRate: number;
|
||||
pickRate: number;
|
||||
avgRating: number;
|
||||
}>;
|
||||
lastFetchedAt: string | null;
|
||||
}
|
||||
|
||||
export interface ApiRecentMatchTeam {
|
||||
side: 100 | 200;
|
||||
win: boolean;
|
||||
objectives?: { baron?: number; dragon?: number; tower?: number };
|
||||
participants: Array<{
|
||||
puuid: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
championId: number;
|
||||
teamPosition: string;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ApiRecentMatchView {
|
||||
matchId: string;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
win: boolean;
|
||||
remake: boolean;
|
||||
championId: number;
|
||||
championLevel: number;
|
||||
teamPosition: string;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
kda: number;
|
||||
rating: number;
|
||||
totalCs: number;
|
||||
csPerMin: number;
|
||||
killParticipation: number;
|
||||
visionScore: number;
|
||||
controlWardsBought: number;
|
||||
wardsPlaced: number;
|
||||
wardsKilled: number;
|
||||
damageDealtToChampions: number;
|
||||
damageTaken: number;
|
||||
goldEarned: number;
|
||||
items: number[];
|
||||
trinket: number;
|
||||
summonerSpells: [number, number];
|
||||
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
||||
teams: ApiRecentMatchTeam[];
|
||||
}
|
||||
|
||||
export interface ApiRecentMatchesResponse {
|
||||
matches: ApiRecentMatchView[];
|
||||
nextCursor: number | null;
|
||||
lastFetchedAt: string | null;
|
||||
season: ApiHistorySeason;
|
||||
}
|
||||
|
||||
export interface ApiInternalMatchCard {
|
||||
matchId: string;
|
||||
title: string;
|
||||
scheduledAt: string;
|
||||
status: 'finished' | 'in-progress';
|
||||
gameCount: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: TeamSide;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string | null;
|
||||
winnerSide: TeamSide | null;
|
||||
gameDuration: number;
|
||||
}>;
|
||||
teams: Array<{
|
||||
side: TeamSide;
|
||||
name: string;
|
||||
members: Array<{
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
profileIconId: number;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ApiInternalMatchListResponse {
|
||||
matches: ApiInternalMatchCard[];
|
||||
nextCursor: number | null;
|
||||
season: ApiHistorySeason;
|
||||
}
|
||||
|
||||
export interface ApiLeaderboardRow {
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
profileIconId: number;
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
winRate: number;
|
||||
totalKills: number;
|
||||
totalDeaths: number;
|
||||
totalAssists: number;
|
||||
kda: number;
|
||||
avgGoldPerMin: number;
|
||||
avgKillParticipation: number;
|
||||
avgCsPerMin: number;
|
||||
avgDamageShare: number;
|
||||
avgVisionScore: number;
|
||||
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
|
||||
topChampions: Array<{ championId: number; games: number; winRate: number }>;
|
||||
}
|
||||
|
||||
export interface ApiLeaderboardResponse {
|
||||
rows: ApiLeaderboardRow[];
|
||||
season: ApiHistorySeason;
|
||||
}
|
||||
|
||||
export interface ApiLeaderHighlight {
|
||||
metric: number;
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
championId?: number;
|
||||
matchId?: string;
|
||||
isSingleGame: boolean;
|
||||
}
|
||||
|
||||
export interface ApiTeamInsightsResponse {
|
||||
season: ApiHistorySeason;
|
||||
sideWinRate: {
|
||||
blue: number;
|
||||
red: number;
|
||||
bluePicks: number;
|
||||
redPicks: number;
|
||||
};
|
||||
topKda: ApiLeaderHighlight | null;
|
||||
mostKills: ApiLeaderHighlight | null;
|
||||
topTeamGpm: ApiLeaderHighlight | null;
|
||||
topKillParticipation: ApiLeaderHighlight | null;
|
||||
bestFarm: ApiLeaderHighlight | null;
|
||||
minGamesThreshold: number;
|
||||
}
|
||||
|
||||
export interface ApiInternalMatchDetailResponse {
|
||||
match: ApiInternalMatchCard;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
teams: Array<{
|
||||
side: TeamSide;
|
||||
win: boolean;
|
||||
objectives: { baron: number; dragon: number; tower: number };
|
||||
participants: Array<{
|
||||
userId: string | null;
|
||||
summonerName: string;
|
||||
side: TeamSide;
|
||||
teamPosition: string;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
cs: number;
|
||||
csPerMin: number;
|
||||
gold: number;
|
||||
gpm: number;
|
||||
damageDealtToChampions: number;
|
||||
damageShare: number;
|
||||
killParticipation: number;
|
||||
visionScore: number;
|
||||
items: number[];
|
||||
trinket: number;
|
||||
summonerSpells: [number, number];
|
||||
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
||||
win: boolean;
|
||||
}>;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ApiUserInternalHistoryResponse {
|
||||
season: ApiHistorySeason;
|
||||
championStats: ApiChampionStatsResponse;
|
||||
summary: ApiRecentSummaryResponse;
|
||||
matches: ApiRecentMatchView[];
|
||||
nextCursor: number | null;
|
||||
lastFetchedAt: string | null;
|
||||
}
|
||||
|
||||
export type LegacyImportJobState =
|
||||
| 'pending'
|
||||
| 'running'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'cancelled';
|
||||
|
||||
export interface LegacyImportMemberWindow {
|
||||
userId: string;
|
||||
puuid: string;
|
||||
displayName: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
isActivated: boolean;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
}
|
||||
|
||||
export interface LegacyImportMembersResponse {
|
||||
members: LegacyImportMemberWindow[];
|
||||
}
|
||||
|
||||
export interface StartLegacyImportRequest {
|
||||
windowStart?: string;
|
||||
windowEnd?: string;
|
||||
memberOverrides?: Array<{
|
||||
userId: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface StartLegacyImportResponse {
|
||||
jobId: string;
|
||||
totalMembers: number;
|
||||
etaSeconds: number;
|
||||
}
|
||||
|
||||
export interface LegacyImportJob {
|
||||
_id: string;
|
||||
jobId: string;
|
||||
communityId: string;
|
||||
triggeredBy: string;
|
||||
startedAt: string;
|
||||
completedAt?: string;
|
||||
state: LegacyImportJobState;
|
||||
windowStart: string;
|
||||
windowEnd: string;
|
||||
memberOverrides: Array<{
|
||||
userId: string;
|
||||
puuid: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
}>;
|
||||
totalMembers: number;
|
||||
processedMembers: number;
|
||||
totalDiscoveredMatchIds: number;
|
||||
totalImportedMatches: number;
|
||||
totalSkippedDuplicate: number;
|
||||
totalErrors: number;
|
||||
averageMemberSeconds?: number;
|
||||
errors?: Array<{
|
||||
puuid?: string;
|
||||
matchId?: string;
|
||||
reason: string;
|
||||
at: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface LegacyImportJobsResponse {
|
||||
jobs: LegacyImportJob[];
|
||||
}
|
||||
|
||||
export interface LegacyMatchListItem {
|
||||
matchId: string;
|
||||
title: string;
|
||||
scheduledAt: string;
|
||||
riotMatchId: string | null;
|
||||
memberCount: number;
|
||||
externalCount: number;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
winnerSide?: TeamSide;
|
||||
}
|
||||
|
||||
export interface LegacyMatchListResponse {
|
||||
matches: LegacyMatchListItem[];
|
||||
nextCursor: number | null;
|
||||
}
|
||||
|
||||
export interface RebuildLegacyMatchesResponse {
|
||||
scanned: number;
|
||||
rebuilt: number;
|
||||
normalizedTitles: number;
|
||||
skippedMissingRaw: number;
|
||||
skippedNoKnownParticipants: number;
|
||||
}
|
||||
|
||||
export type ApiRiotJobPriority = 'high' | 'low';
|
||||
export type ApiRiotJobState = 'queued' | 'processing' | 'completed' | 'failed';
|
||||
|
||||
export interface ApiEnqueueRefreshResult {
|
||||
parentJobId: string;
|
||||
subJobs: Array<{
|
||||
jobId: string;
|
||||
queueGroup: RiotQueueGroup;
|
||||
alreadyQueued: boolean;
|
||||
etaSeconds: number;
|
||||
queuePosition: number;
|
||||
}>;
|
||||
totalEtaSeconds: number;
|
||||
}
|
||||
|
||||
export interface ApiRiotRefreshEvent {
|
||||
parentJobId: string;
|
||||
jobId: string;
|
||||
queueGroup: RiotQueueGroup;
|
||||
puuid: string;
|
||||
state: ApiRiotJobState;
|
||||
error?: string;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||
import type { ApiAuction, Position, TeamSide } from './types';
|
||||
|
||||
type ConnectionStatus =
|
||||
| 'idle'
|
||||
| 'connecting'
|
||||
| 'connected'
|
||||
| 'disconnected'
|
||||
| 'error';
|
||||
|
||||
interface BidPayload {
|
||||
side: TeamSide;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
}
|
||||
|
||||
export function useAuctionSocket(matchId: string | undefined) {
|
||||
const authUserId = useAuthUserId();
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
||||
const [connectionStatus, setConnectionStatus] =
|
||||
useState<ConnectionStatus>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!matchId) {
|
||||
setAuction(null);
|
||||
setConnectionStatus('idle');
|
||||
return;
|
||||
}
|
||||
|
||||
let disposed = false;
|
||||
setConnectionStatus('connecting');
|
||||
setError(null);
|
||||
|
||||
void (async () => {
|
||||
const accessToken = await acquireAccessToken().catch((error) => {
|
||||
console.warn('Failed to acquire socket access token:', error);
|
||||
return null;
|
||||
});
|
||||
if (disposed) return;
|
||||
|
||||
const socket = io(`${API_BASE_URL}/auction`, {
|
||||
transports: ['websocket'],
|
||||
auth: accessToken
|
||||
? { token: accessToken }
|
||||
: authUserId
|
||||
? { 'x-auth-user-id': authUserId }
|
||||
: {},
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.on('connect', () => {
|
||||
setConnectionStatus('connected');
|
||||
socket.emit('join', { matchId });
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setConnectionStatus('disconnected');
|
||||
});
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
setAuction(nextAuction);
|
||||
setError(null);
|
||||
});
|
||||
|
||||
socket.on('error', (payload: { message?: string }) => {
|
||||
setConnectionStatus('error');
|
||||
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
||||
});
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
const socket = socketRef.current;
|
||||
socket?.removeAllListeners();
|
||||
socket?.disconnect();
|
||||
socketRef.current = null;
|
||||
setConnectionStatus('idle');
|
||||
};
|
||||
}, [authUserId, matchId]);
|
||||
|
||||
function emit(eventName: string, payload?: unknown) {
|
||||
const socket = socketRef.current;
|
||||
if (!socket || !socket.connected) {
|
||||
setError('소켓이 아직 연결되지 않았습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
if (payload === undefined) {
|
||||
socket.emit(eventName);
|
||||
return;
|
||||
}
|
||||
|
||||
socket.emit(eventName, payload);
|
||||
}
|
||||
|
||||
return {
|
||||
auction,
|
||||
connectionStatus,
|
||||
error,
|
||||
placeBid(payload: BidPayload) {
|
||||
emit('bid', payload);
|
||||
},
|
||||
openBidding() {
|
||||
emit('open-bidding', {});
|
||||
},
|
||||
markSold(assignedPosition?: Position) {
|
||||
emit('sold', assignedPosition ? { assignedPosition } : {});
|
||||
},
|
||||
next() {
|
||||
emit('next', {});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { API_BASE_URL } from '../config';
|
||||
import type { ApiRiotRefreshEvent } from './types';
|
||||
|
||||
type ConnectionStatus =
|
||||
| 'idle'
|
||||
| 'connecting'
|
||||
| 'connected'
|
||||
| 'disconnected'
|
||||
| 'error';
|
||||
|
||||
export function useRiotRefreshSocket({
|
||||
puuid,
|
||||
parentJobId,
|
||||
onEvent,
|
||||
}: {
|
||||
puuid?: string;
|
||||
parentJobId?: string;
|
||||
onEvent: (event: ApiRiotRefreshEvent) => void;
|
||||
}) {
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
const onEventRef = useRef(onEvent);
|
||||
const [connectionStatus, setConnectionStatus] =
|
||||
useState<ConnectionStatus>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
onEventRef.current = onEvent;
|
||||
}, [onEvent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!puuid && !parentJobId) {
|
||||
setConnectionStatus('idle');
|
||||
return;
|
||||
}
|
||||
|
||||
setConnectionStatus('connecting');
|
||||
setError(null);
|
||||
|
||||
const socket = io(`${API_BASE_URL}/riot-refresh`, {
|
||||
transports: ['websocket'],
|
||||
});
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.on('connect', () => {
|
||||
setConnectionStatus('connected');
|
||||
socket.emit('subscribe', { puuid, parentJobId });
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
setConnectionStatus('disconnected');
|
||||
});
|
||||
|
||||
socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => {
|
||||
onEventRef.current(event);
|
||||
});
|
||||
|
||||
socket.on('error', (payload: { message?: string }) => {
|
||||
setConnectionStatus('error');
|
||||
setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.');
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.removeAllListeners();
|
||||
socket.disconnect();
|
||||
socketRef.current = null;
|
||||
setConnectionStatus('idle');
|
||||
};
|
||||
}, [parentJobId, puuid]);
|
||||
|
||||
return { connectionStatus, error };
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { setAuthUserId, useAuthUserId } from '../config';
|
||||
|
||||
export default function DevAuthSwitcher() {
|
||||
const authUserId = useAuthUserId();
|
||||
const queryClient = useQueryClient();
|
||||
const [inputValue, setInputValue] = useState(authUserId ?? '');
|
||||
|
||||
useEffect(() => {
|
||||
setInputValue(authUserId ?? '');
|
||||
}, [authUserId]);
|
||||
|
||||
if (!import.meta.env.DEV) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function updateAuthUserId(nextValue: string | null) {
|
||||
setAuthUserId(nextValue);
|
||||
void queryClient.invalidateQueries();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed right-4 bottom-4 z-50 w-72 border border-base-content/10 bg-base-100/95 backdrop-blur px-3 py-3 shadow-xl">
|
||||
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
|
||||
Dev Auth
|
||||
</div>
|
||||
<div className="mt-2 text-[11px] text-base-content/45">
|
||||
X-Auth-User-Id
|
||||
</div>
|
||||
<input
|
||||
value={inputValue}
|
||||
onChange={(event) => setInputValue(event.target.value)}
|
||||
placeholder="Mongo User ID"
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-xs text-base-content focus:outline-none focus:border-primary/30"
|
||||
/>
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-xs px-3"
|
||||
onClick={() => updateAuthUserId(inputValue)}
|
||||
>
|
||||
Set
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-xs px-3"
|
||||
onClick={() => updateAuthUserId(null)}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2 text-[10px] text-base-content/35 break-all">
|
||||
현재값: {authUserId ?? '없음'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
export type DevCaptainSide = 'spectator' | 'blue' | 'red';
|
||||
|
||||
const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId';
|
||||
const DEV_CAPTAIN_SIDE_STORAGE_KEY = 'lolympus.devCaptainSide';
|
||||
const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed';
|
||||
const CAPTAIN_SIDE_CHANGED_EVENT = 'lolympus:captain-side-changed';
|
||||
|
||||
export const API_BASE_URL = (
|
||||
import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000'
|
||||
).replace(/\/$/, '');
|
||||
|
||||
export const DEFAULT_COMMUNITY_ID = (
|
||||
import.meta.env.VITE_DEFAULT_COMMUNITY_ID ?? ''
|
||||
).trim();
|
||||
|
||||
function dispatchWindowEvent(eventName: string) {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.dispatchEvent(new Event(eventName));
|
||||
}
|
||||
|
||||
function subscribeToWindowChanges(eventName: string, callback: () => void) {
|
||||
if (typeof window === 'undefined') {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const handleChange = () => callback();
|
||||
window.addEventListener(eventName, handleChange);
|
||||
window.addEventListener('storage', handleChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(eventName, handleChange);
|
||||
window.removeEventListener('storage', handleChange);
|
||||
};
|
||||
}
|
||||
|
||||
export function getAuthUserId(): string | null {
|
||||
if (!import.meta.env.DEV) return null;
|
||||
if (typeof window === 'undefined') return null;
|
||||
const value = window.localStorage.getItem(AUTH_USER_ID_STORAGE_KEY)?.trim();
|
||||
return value ? value : null;
|
||||
}
|
||||
|
||||
export function setAuthUserId(userId: string | null) {
|
||||
if (!import.meta.env.DEV) return;
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
if (!userId?.trim()) {
|
||||
window.localStorage.removeItem(AUTH_USER_ID_STORAGE_KEY);
|
||||
} else {
|
||||
window.localStorage.setItem(AUTH_USER_ID_STORAGE_KEY, userId.trim());
|
||||
}
|
||||
|
||||
dispatchWindowEvent(AUTH_USER_CHANGED_EVENT);
|
||||
}
|
||||
|
||||
export function getDevCaptainSide(): DevCaptainSide {
|
||||
if (typeof window === 'undefined') return 'spectator';
|
||||
|
||||
const value = window.localStorage.getItem(
|
||||
DEV_CAPTAIN_SIDE_STORAGE_KEY,
|
||||
) as DevCaptainSide | null;
|
||||
|
||||
if (value === 'blue' || value === 'red' || value === 'spectator') {
|
||||
return value;
|
||||
}
|
||||
|
||||
return 'spectator';
|
||||
}
|
||||
|
||||
export function setDevCaptainSide(side: DevCaptainSide) {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.localStorage.setItem(DEV_CAPTAIN_SIDE_STORAGE_KEY, side);
|
||||
dispatchWindowEvent(CAPTAIN_SIDE_CHANGED_EVENT);
|
||||
}
|
||||
|
||||
export function useAuthUserId(): string | null {
|
||||
return useSyncExternalStore<string | null>(
|
||||
(callback) => subscribeToWindowChanges(AUTH_USER_CHANGED_EVENT, callback),
|
||||
getAuthUserId,
|
||||
() => null,
|
||||
);
|
||||
}
|
||||
|
||||
export function useDevCaptainSide(): DevCaptainSide {
|
||||
return useSyncExternalStore<DevCaptainSide>(
|
||||
(callback) => subscribeToWindowChanges(CAPTAIN_SIDE_CHANGED_EVENT, callback),
|
||||
getDevCaptainSide,
|
||||
() => 'spectator',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
export default function AuthCallbackPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => navigate('/', { replace: true }), 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20 text-center">
|
||||
<span className="text-sm text-base-content/45">로그인 처리 중...</span>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useMsal } from "@azure/msal-react";
|
||||
import {
|
||||
isMsalConfigured,
|
||||
MSAL_API_SCOPE,
|
||||
msalInstance,
|
||||
} from "../lib/auth/msal.config";
|
||||
|
||||
function LoginButton() {
|
||||
const { instance } = useMsal();
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm px-5"
|
||||
onClick={() =>
|
||||
void instance.loginRedirect({
|
||||
scopes: [MSAL_API_SCOPE],
|
||||
prompt: "select_account",
|
||||
})
|
||||
}
|
||||
>
|
||||
Entra ID 로 로그인
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20">
|
||||
<div className="max-w-md border border-base-content/10 bg-base-100 p-6 shadow-sm">
|
||||
<h1 className="text-xl font-bold tracking-tight">로그인</h1>
|
||||
<p className="mt-2 text-sm text-base-content/50">
|
||||
Entra ID 계정으로 LOLYMPUS 정보를 불러옵니다.
|
||||
</p>
|
||||
<div className="mt-5">
|
||||
{isMsalConfigured && msalInstance ? (
|
||||
<LoginButton />
|
||||
) : (
|
||||
<div className="text-sm text-amber-600">
|
||||
MSAL 환경변수 설정이 필요합니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user