.
This commit is contained in:
1 parent
30dfb7ce58
commit
5af2c80cd1
33 files changed
+3806
-1440
No files matched your search
@@ -0,0 +1,85 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
|
||||
import { apiFetch } from '../lib/api';
|
||||
import type {
|
||||
ApiAuction,
|
||||
ApiCommunity,
|
||||
ApiMatch,
|
||||
MatchStatus,
|
||||
MatchesResponse,
|
||||
MeResponse,
|
||||
} from './types';
|
||||
|
||||
interface MatchesQueryOptions {
|
||||
status?: MatchStatus;
|
||||
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}`),
|
||||
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),
|
||||
);
|
||||
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}`),
|
||||
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`),
|
||||
enabled: Boolean(communityId && matchId),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMe() {
|
||||
const authUserId = useAuthUserId();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['me', authUserId],
|
||||
queryFn: () => apiFetch<MeResponse>('/me'),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
import type {
|
||||
ApiAuction,
|
||||
ApiAuctionPlayerSnapshot,
|
||||
ApiAuctionTeam,
|
||||
ApiMatch,
|
||||
ApiMatchParticipant,
|
||||
ApiPositionPreference,
|
||||
ApiTierInfo,
|
||||
MatchStatus,
|
||||
Position,
|
||||
TeamSide,
|
||||
} 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;
|
||||
joined: boolean;
|
||||
participants: ParticipantView[];
|
||||
teams: TeamView[];
|
||||
result?: {
|
||||
winner: string;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
};
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
schedule: { time: string; label: string }[];
|
||||
}
|
||||
|
||||
export interface AuctionPlayerView extends ParticipantView {
|
||||
masteries: {
|
||||
championName: string;
|
||||
championId: string;
|
||||
level: number;
|
||||
points: number;
|
||||
}[];
|
||||
recentStats: {
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
kda: {
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
};
|
||||
avgCs: number;
|
||||
};
|
||||
}
|
||||
|
||||
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: '챌린저',
|
||||
};
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
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, 3).map((mastery) => ({
|
||||
championName: mastery.championName ?? mastery.championId,
|
||||
championId: mastery.championId,
|
||||
level: mastery.level,
|
||||
points: mastery.points,
|
||||
})),
|
||||
recentStats: {
|
||||
games: player.recentStatsSummary?.games ?? 0,
|
||||
wins: player.recentStatsSummary?.wins ?? 0,
|
||||
losses: player.recentStatsSummary?.losses ?? 0,
|
||||
kda: {
|
||||
kills: player.recentStatsSummary?.avgKills ?? 0,
|
||||
deaths: player.recentStatsSummary?.avgDeaths ?? 0,
|
||||
assists: player.recentStatsSummary?.avgAssists ?? 0,
|
||||
},
|
||||
avgCs: Math.round(player.recentStatsSummary?.avgCs ?? 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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: {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
kda: { kills: 0, deaths: 0, assists: 0 },
|
||||
avgCs: 0,
|
||||
},
|
||||
}
|
||||
: {
|
||||
...createFallbackParticipant(member.userId),
|
||||
masteries: [],
|
||||
recentStats: {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
kda: { kills: 0, deaths: 0, assists: 0 },
|
||||
avgCs: 0,
|
||||
},
|
||||
});
|
||||
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
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
|
||||
? 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,
|
||||
joined: Boolean(match.joined),
|
||||
participants,
|
||||
teams,
|
||||
result: match.result
|
||||
? {
|
||||
winner: winnerTeam?.name ?? sideLabel(match.result.winnerSide),
|
||||
blueScore: match.result.blueScore,
|
||||
redScore: match.result.redScore,
|
||||
}
|
||||
: 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,207 @@
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
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 {
|
||||
championId: string;
|
||||
championName?: string;
|
||||
level: number;
|
||||
points: number;
|
||||
}
|
||||
|
||||
export interface ApiRiotRecentStatsSummary {
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
avgCs: number;
|
||||
mostPlayedChampionIds: string[];
|
||||
extras?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
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 ApiMatchResult {
|
||||
winnerSide: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
mvpUserId?: string;
|
||||
riotMatchIds: string[];
|
||||
}
|
||||
|
||||
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;
|
||||
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 MeResponse {
|
||||
user: ApiUser | null;
|
||||
}
|
||||
|
||||
export interface MatchesResponse {
|
||||
matches: ApiMatch[];
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
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;
|
||||
}
|
||||
|
||||
const socket = io(`${API_BASE_URL}/auction`, {
|
||||
transports: ['websocket'],
|
||||
auth: authUserId ? { 'x-auth-user-id': authUserId } : {},
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
setConnectionStatus('connecting');
|
||||
setError(null);
|
||||
|
||||
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 () => {
|
||||
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', {});
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user