22 KiB
Frontend ↔ Backend 통합 플랜 (Lolympus Tournament Support)
대상: codex에 이어서 작업 가능한 수준의 실행 플랜 레포:
/Users/dahyeon/source/lolympus-tournament-support(pnpm workspace) 작성 기준: 2026-04-24
1. Context
apps/web(React 19 + Vite + React Router 7)은 현재 src/mock.ts와 src/auction-mock.ts의 하드코딩된 더미 데이터로만 화면을 그립니다. 경매 페이지는 setInterval 기반 클라이언트 사이드 시뮬레이터(createMockAuction())로 동작합니다.
apps/api(NestJS 11 + Mongoose 9)는 Community/User/Match/Auction 스키마와 CRUD 엔드포인트, RBAC 가드(@Roles), 글로벌 ValidationPipe, X-Auth-User-Id 헤더 기반 임시 인증까지 구축되어 있습니다. 하지만 경매 실시간 푸시(WebSocket) 미구현, CORS 미설정, MatchParticipant 스냅샷에 티어 정보 없음, /me 같은 편의 엔드포인트 없음이 통합의 걸림돌입니다.
이번 작업의 목표
- 경매 페이지가 서버 주도 타이머·상태로 10명 관전 + 2명 입찰을 실시간 동기화하도록 WebSocket 게이트웨이를 API에 추가
- 프론트엔드의 모든 mock import를 제거하고 API 클라이언트 + React Query + Socket.IO 클라이언트로 교체
- 초기 MVP는 단일 기본 커뮤니티 전제 (env
VITE_DEFAULT_COMMUNITY_ID) - 로그인 UI는 이번 범위에서 제외. admin 기능은 개발자용 "User ID 수동 입력" 위젯으로 임시 처리
MatchParticipant스냅샷에tier필드 추가 (참여 시점의 primary RiotAccount tier를 복사)
비목표 (이번 작업에 포함하지 않음)
- 카카오/디스코드 OAuth 로그인 플로우
- 다중 커뮤니티 전환 UI
- Riot API 실시간 동기화 UI (기존
RiotAccountService는 그대로 둠) - 매치 결과 기록 UI (
MatchResult) - 포스트-경매 Riot 토너먼트 코드 발급
2. 현재 상태 정리 (실사 결과)
2.1 백엔드에 이미 있는 것
| 영역 | 파일 | 상태 |
|---|---|---|
| Community CRUD + owner 트랜잭션 | apps/api/src/modules/community/* |
✅ |
| Match CRUD + 참여(join) | apps/api/src/modules/match/* |
✅ |
| Auction 시작/입찰/낙찰/다음/리셋 | apps/api/src/modules/auction/* |
✅ (HTTP만) |
| 스키마 (Community/User/Match/Auction/RiotMatch) | apps/api/src/modules/global/database/schema.ts |
✅ |
@Roles + RolesGuard + CurrentUser |
apps/api/src/modules/auth/* |
✅ |
글로벌 ValidationPipe |
apps/api/src/main.ts |
✅ |
2.2 백엔드에 없는 것 (이번에 추가)
- CORS — Vite dev는
http://localhost:5173, API는http://localhost:3000.app.enableCors()필요 - WebSocket (Socket.IO) 게이트웨이 — auction 상태 푸시 + 클라이언트 입찰 수신
- 서버 주도 타이머 — 현재 auction 문서에
maxTimerSeconds만 있음. 입찰 시 갱신되는currentDeadline: Date필드 + 만료 자동markSold스케줄러 필요 MatchParticipant.tier— 참여 시 primary RiotAccount의 primary queue tier(solo 5x5)를 snapshot으로 복사GET /me— 현재X-Auth-User-Id헤더의 User 반환 (헤더 없으면null). 프론트에서 admin 기능 가시성 판단용GET /communities/:communityId— 프론트 헤더에 커뮤니티 이름 표시용mapId: number→ 프론트 라벨 매핑 유틸(프론트 쪽). 백엔드는 그대로
2.3 프론트엔드에 없는 것 (이번에 추가)
- API 클라이언트 (
src/lib/api.ts) — fetch 래퍼,X-Auth-User-Id주입 @tanstack/react-query+QueryClientProvidersocket.io-client+useAuctionSocket훅src/config.ts—VITE_API_BASE_URL,VITE_DEFAULT_COMMUNITY_ID, localStorageX-Auth-User-Id관리- 백엔드 스키마에 대응하는 프론트 타입 (
src/api/types.ts) - 백엔드
Match/Auction→ 프론트MatchDetail/AuctionState매핑 함수 (src/api/mappers.ts) - 개발자용 "User ID 주입" 토글 UI (admin 기능 테스트용, 프로덕션 빌드에선 숨김)
2.4 데이터 모델 차이 요약
| 프론트 모델 | 백엔드 모델 | 매핑 전략 |
|---|---|---|
MatchDetail.date/time (한국어 string) |
Match.scheduledAt: Date |
프론트에서 Intl.DateTimeFormat('ko-KR')로 포맷 |
MatchDetail.map: string ("소환사의 협곡") |
Match.mapId: number (11) |
프론트 mapIdToLabel 유틸 |
Participant.tier: {previousSeason, current, peak} |
추가 필요: MatchParticipant.tier 스냅샷 |
백엔드에 필드 추가 후 프론트가 그대로 읽음 (프론트 TierInfo는 백엔드 원본 형태로 리팩터) |
Team.participants[].assignedPosition |
MatchTeam.members[].assignedPosition |
프론트가 match.participants와 match.teams를 조합해서 표시 |
AuctionPlayer.tier (단일) |
AuctionPlayerSnapshot.tiers: TierInfo[] |
프론트에서 queueType === 'RANKED_SOLO_5x5' 필터 후 대표 선택 |
AuctionPlayer.masteries[].championName |
ChampionMasteryEntry.championName (optional) |
프론트가 fallback 처리 |
AuctionState.timer (초, 카운트다운) |
서버 currentDeadline: Date |
프론트가 deadline - now로 매 틱 계산 |
3. 실행 계획
단계는 독립적이지 않고 순차 진행 권장. Phase 0 → 1 → 2 → 3 순서.
Phase 0 — 백엔드 선행 보강 (apps/api)
0.1 CORS 활성화
파일: apps/api/src/main.ts
app.enableCors({
origin: process.env.WEB_ORIGIN?.split(",") ?? ["http://localhost:5173"],
credentials: true,
allowedHeaders: ["Content-Type", "X-Auth-User-Id"],
});
프로덕션용 origin은 project.env의 WEB_ORIGIN으로 주입.
0.2 MatchParticipant.tier 스냅샷 필드 추가
파일: apps/api/src/modules/global/database/schema.ts
MatchParticipantinterface + sub-schema에tier?: TierInfo추가 (optional — Riot 계정이 없는 유저도 참여 가능해야 하면)MatchService.join()(apps/api/src/modules/match/match.service.ts라인 93~)에서primaryRiot.tiers.find(t => t.queueType === 'RANKED_SOLO_5x5') ?? primaryRiot.tiers[0]를 복사- 기존 데이터 마이그레이션 없이 optional이라 호환성 유지
0.3 /me + /communities/:id 편의 엔드포인트
신규 파일: apps/api/src/modules/user/user.controller.ts, user.module.ts
@Controller("me")
class MeController {
@Get()
me(@CurrentUser() user: UserDocument | undefined) {
return user ? { user } : { user: null };
}
}
Community 쪽 (community.controller.ts):
@Get(':communityId')
async getCommunity(@Param('communityId', ParseObjectIdPipe) id) {
return this.communityService.getById(id); // 서비스에 메서드 추가
}
0.4 Auction WebSocket 게이트웨이 (핵심)
의존성 설치: pnpm --filter api add @nestjs/websockets @nestjs/platform-socket.io socket.io
신규 파일: apps/api/src/modules/auction/auction.gateway.ts
네임스페이스·룸 구조:
- 네임스페이스:
/auction - 룸 이름:
matchId문자열
이벤트 스펙:
| 방향 | 이벤트 | payload |
|---|---|---|
| server→client | state |
AuctionDocument (직렬화) |
| server→client | tick |
{ deadline: string, serverTime: string } |
| server→client | error |
{ message: string } |
| client→server | join |
{ matchId: string } |
| client→server | bid |
{ side, amount, bidderUserId? } |
| client→server | open-bidding |
{} |
| client→server | sold |
{ assignedPosition? } |
| client→server | next |
{} |
구현 포인트:
handleConnection/handleDisconnect에서 Socket.IO의 rooms 표준 사용- 클라이언트
join시 해당 matchId 룸에 입장 + 현재state푸시 - 입찰/낙찰/다음 이벤트는 기존
AuctionService메서드 재사용. 결과 상태를 해당 룸에 브로드캐스트 AuctionService가 phase 전이 시마다deadline: Date계산해서 Auction 문서에 저장 (AuctionSchema에currentDeadline?: Date추가)- 타이머 만료 자동 처리는 Phase 0에선 생략하고, 클라이언트가 deadline 지나면 "시간 종료" 표시만. 자동
markSold는 후속 작업 (SchedulerRegistry+setTimeout필요). 트러스트 전제라 팀장이 수동 sold 하면 충분.
AuthMiddleware는 socket.io 연결에 적용되지 않음: 게이트웨이 자체에서 @ConnectedSocket()의 handshake headers 또는 auth payload에서 x-auth-user-id를 읽어 옵션으로 취급. 권한 필요한 이벤트(open-bidding, sold, next)는 일단 무검증 유지 (트러스트 전제). bid만 payload의 bidderUserId를 검증해서 해당 팀의 captainUserId와 일치하는지 정도 체크하면 고의 방해 방지 최소선은 만족.
0.5 AuctionSchema.currentDeadline 추가
파일: apps/api/src/modules/global/database/schema.ts
- interface
Auction에currentDeadline?: Date - Schema 필드 추가
AuctionService.openBidding()과placeBid()에서new Date(Date.now() + auction.maxTimerSeconds * 1000)로 갱신placeBid시엔Math.max(5, remainingSeconds)보장 (기존 프론트 mock 로직과 동일: 최소 5초)
markSold/next시엔undefined로 리셋
0.6 AppModule 등록
파일: apps/api/src/app.module.ts
UserModuleimportAuctionModule에서 게이트웨이 providers 등록 (AuctionGateway+AuctionService는 그대로)
0.7 검증 (Phase 0 종료 시)
cd apps/api
./node_modules/.bin/tsc --noEmit
pnpm start:dev
curl -H "X-Auth-User-Id: <id>" http://localhost:3000/me로/me확인- socket.io 클라이언트(또는
wscat)로ws://localhost:3000/auction연결 +join이벤트 →state수신 확인
Phase 1 — 프론트엔드 인프라 구축 (apps/web)
1.1 의존성 설치
pnpm --filter web add @tanstack/react-query socket.io-client
pnpm --filter web add -D @tanstack/react-query-devtools
1.2 환경 변수
신규 파일: apps/web/.env.development (기존 있으면 추가)
VITE_API_BASE_URL=http://localhost:3000
VITE_DEFAULT_COMMUNITY_ID=<Phase 3에서 생성한 커뮤니티 _id>
신규 파일: apps/web/src/config.ts
API_BASE_URL,DEFAULT_COMMUNITY_IDexportgetAuthUserId()/setAuthUserId(id | null)(localStoragelolympus.authUserId)
1.3 API 클라이언트
신규 파일: apps/web/src/lib/api.ts
apiFetch<T>(path, init?): 베이스 URL 붙이고,X-Auth-User-Id자동 주입, JSON 파싱, 4xx/5xx는ApiErrorthrow- 응답 타입은 제네릭
1.4 타입 정의 (백엔드 미러)
신규 파일: apps/web/src/api/types.ts
Position,TeamSide,MatchStatus,AuctionPhase같은 유니온은 복붙TierInfo,ChampionMasteryEntry,RiotRecentStatsSummary등 sub-typeApiCommunity,ApiUser,ApiMatch,ApiAuction— 응답 형태 그대로_id: string(ObjectId 직렬화),createdAt/updatedAt: string(ISO)
타입 중복은 MVP에선 감수. 나중에
packages/shared-types생성 고려.
1.5 매핑 레이어
신규 파일: apps/web/src/api/mappers.ts
mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailmapApiAuctionToAuctionState(auction: ApiAuction, serverNow?: Date): AuctionStatemapIdToLabel(mapId: number): string—11 → '소환사의 협곡',12 → '칼바람 나락', ...formatKoreanDate(date: Date): { date, time }selectPrimaryTier(tiers: TierInfo[]): TierInfo | undefined
기존
apps/web/src/mock.ts의MatchDetail/Participant타입은 유지한 채로 매퍼가 채움. 이후 Phase 2에서 점진 삭제.
1.6 React Query 설정
파일 수정: apps/web/src/main.tsx
QueryClientProvider로 감싸기- staleTime 10s, cacheTime 5min 기본값
1.7 Socket 훅
신규 파일: apps/web/src/api/useAuctionSocket.ts
useAuctionSocket(matchId: string)훅- 내부:
useEffect로io(API_BASE_URL + '/auction', { auth: { 'x-auth-user-id': getAuthUserId() } }) joinemit 후state/tick/error이벤트 구독- state는
useState로 저장, 반환:{ state, placeBid, openBidding, markSold, next, connectionStatus }
1.8 개발자용 User 주입 위젯
신규 파일: apps/web/src/components/DevAuthSwitcher.tsx
- 우하단 플로팅 패널. input + "Set"/"Clear" 버튼. localStorage 값 표시
import.meta.env.DEV일 때만 렌더
Phase 2 — 페이지 교체 (apps/web)
2.1 HomePage
파일: apps/web/src/pages/HomePage.tsx
- mock import 제거
useQuery(['matches', communityId, 'upcoming'])→GET /communities/:id/matches?status=recruiting&limit=20useQuery(['matches', communityId, 'finished'])→GET /communities/:id/matches?status=finished&limit=10- "다음 내전"은 upcoming의 첫 요소
- 각 카드는
mapApiMatchToMatchDetail의 축약 버전으로
2.2 MatchDetailPage
파일: apps/web/src/pages/MatchDetailPage.tsx
useQuery(['match', matchId])→GET /communities/:id/matches/:matchIdmapApiMatchToMatchDetail()적용- 참가자 티어는
participant.tier직접 사용 (백엔드 snapshot) - "경매 시작" 버튼은
/me결과의 role이 admin/owner일 때만 보여주기 (admin 전용)
2.3 AuctionPage
파일: apps/web/src/pages/AuctionPage.tsx
createMockAuctionimport 제거- 초기 상태:
useQuery(['auction', matchId])→GET /communities/:id/matches/:matchId/auction - 이후:
useAuctionSocket(matchId)로 실시간 갱신 - 타이머:
state.currentDeadline과Date.now()차이로 클라이언트 카운트다운 - "입찰" 버튼:
placeBid({side, amount})호출 (내부적으로 socket emit) - "공개"/"낙찰"/"다음" 버튼(팀장용): socket emit — 페이지에 세 버튼 노출 (트러스트 전제)
- localStorage에 자기가 어느 팀장인지 저장하는 토글 추가 (dev 편의)
2.4 mock 파일 제거
apps/web/src/mock.ts— Position/TierInfo/Participant 같은 타입만src/api/types.ts로 흡수 후 삭제apps/web/src/auction-mock.ts— 전부 삭제apps/web/src/auction-types.ts— 프론트 전용 파생 타입만 남기고 백엔드 응답 타입은api/types.ts로
Phase 3 — E2E 검증 및 시드
3.1 시드 데이터 생성 스크립트
신규 파일: apps/api/src/seed.ts (또는 ad-hoc)
CommunityService.createCommunityWithOwner({ name: 'Dev Community', owner: { kakaoTalkNickname: 'DevOwner' } })- 참가자 유저 10명 생성 (Riot 계정 더미 + tiers 채움 — 기존 mock 데이터를 DB로 이식)
- 매치 3개 (recruiting 1, team-built 1, finished 1)
- 반환된
communityId를.env.development에 복사
실행:
pnpm --filter api exec ts-node src/seed.ts
3.2 통합 smoke test
pnpm --filter api start:devpnpm --filter web dev- 브라우저에서
http://localhost:5173:- HomePage에 시드 매치 3개 표시되는지
- MatchDetailPage에서 참가자 티어 정보 렌더링되는지
- DevAuthSwitcher로 owner User ID 주입 → 경매 시작 버튼 보이는지
- AuctionPage 두 탭 열어서 한쪽 입찰 시 다른 쪽 실시간 반영되는지
tsc --noEmit과pnpm --filter web build무오류 확인
4. 파일별 수정/신규 체크리스트
apps/api 수정
src/main.ts— CORSsrc/modules/global/database/schema.ts—MatchParticipant.tier?,Auction.currentDeadline?src/modules/match/match.service.ts::join— tier 스냅샷 복사src/modules/auction/auction.service.ts—openBidding/placeBid에서currentDeadline갱신,markSold/next에서 리셋src/modules/community/community.controller.ts+community.service.ts—getById+GET /communities/:idsrc/app.module.ts—UserModule,AuctionGatewayprovider 등록
apps/api 신규
src/modules/user/user.module.tssrc/modules/user/user.controller.ts(GET /me)src/modules/auction/auction.gateway.tssrc/seed.ts(선택)
apps/web 수정
src/main.tsx—QueryClientProvidersrc/App.tsx— DevAuthSwitcher 마운트src/pages/HomePage.tsx— react-query 연동src/pages/MatchDetailPage.tsx— react-query 연동src/pages/AuctionPage.tsx— socket 훅 연동
apps/web 신규
.env.developmentsrc/config.tssrc/lib/api.tssrc/api/types.tssrc/api/mappers.tssrc/api/useAuctionSocket.tssrc/api/hooks.ts(선택 —useMatches,useMatch,useAuction,useMe)src/components/DevAuthSwitcher.tsx
apps/web 삭제
src/mock.ts(타입은src/api/types.ts로 흡수 후)src/auction-mock.ts
5. 재사용할 기존 유틸
| 용도 | 위치 | 재사용 포인트 |
|---|---|---|
| ObjectId 파라미터 파싱 | apps/api/src/modules/common/parse-object-id.pipe.ts |
새 엔드포인트(getCommunity, me)에도 적용 |
| 트랜잭션 세션 생성 | apps/api/src/modules/global/database/connection.service.ts::createSession |
AuctionGateway에서 원자적 상태 전이가 필요한 경우 |
@CurrentUser() |
apps/api/src/modules/auth/current-user.decorator.ts |
/me에서 그대로 사용 |
| Role 매핑 | apps/api/src/modules/auth/permissions.ts::roleHasPermission |
프론트에 권한 표시 JSON 내려줄 때 참고 |
| 포지션 라벨/아이콘 | apps/web/src/assets/position/* + mock.ts의 positionLabel/positionIcon |
src/api/mappers.ts로 이동 |
6. 위험 요소 & 주의사항
- Socket.IO 인증 미적용: MVP에선 WebSocket 연결에 인증을 강제하지 않음. 고의 방해 시나리오 대비는
bid이벤트의bidderUserId가 해당 팀captainUserId와 일치하는지만 체크. 프로덕션 전환 전에 JWT 핸드셰이크로 교체. - 타이머 만료 자동 sold 미구현: 팀장이 수동으로 "낙찰" 누르는 흐름. 이게 불편하면 후속 작업으로
SchedulerRegistry타이머 추가. - Mongoose
HydratedDocument직렬화:JSON.stringify는toJSON을 거치지만_id가 ObjectId 객체로 나올 수 있음. 엔드포인트에서.lean()또는toObject({ versionKey: false })적용 고려 — 또는 프론트에서String(_id)처리. - 프론트 타입 중복:
apps/web/src/api/types.ts가 백엔드 스키마와 갈라질 수 있음. Phase 3 이후packages/shared-types워크스페이스로 승격 권장. - 시드 데이터의 communityId 동기화:
.env.development에 하드코딩되므로 재시드 시 값 바뀜.seed.ts마지막에.env.development를 갱신하도록 하면 편함. forbidNonWhitelisted: true: DTO에 없는 필드는 400. 프론트 요청 페이로드 구성 시 주의.- Riot 계정 없는 유저 참여:
MatchService.join은 현재primaryRiot없어도undefined로 저장.tier필드도 optional로 유지해야 기존 흐름 유지.
7. 검증 체크리스트 (최종)
pnpm --filter api run build무오류pnpm --filter web run build무오류curl -i http://localhost:3000/me→{user: null}, 헤더 넣으면 user 객체curl http://localhost:3000/communities/<id>/matches→ 시드 매치 목록- 브라우저 HomePage 렌더 OK
- MatchDetailPage에 티어 표시 OK
- AuctionPage 두 탭 open → 한쪽 bid 하면 다른 쪽
state이벤트로 즉시 갱신 - DevAuthSwitcher로 owner ID 주입 시에만 "경매 시작" 버튼 노출
- 비 admin 상태에선 admin 엔드포인트 호출 시 401/403 응답이 UI에 에러 토스트로 노출
8. 작업 순서 (codex 핸드오프용)
- Phase 0 (백엔드 보강) — 스키마 변경 → 서비스 갱신 → 게이트웨이 → CORS/ME. 빌드 확인.
- Phase 1 (프론트 인프라) — deps 설치 → config/api/types/mappers → QueryClientProvider.
- Phase 3의 3.1 시드 먼저 돌려서
communityId확보 →.env.development업데이트. - Phase 2 (페이지 교체) — HomePage → MatchDetailPage → AuctionPage 순서.
- Phase 3의 3.2 E2E 스모크 테스트.
각 Phase 종료마다 tsc --noEmit으로 타입 검증, 필요시 pnpm lint 실행.