Skip to content

[FEAT] 채팅 REST 및 소켓 연동 훅 추가 - #65

Merged
youngmis merged 2 commits into
devfrom
feature/chat-rest-socket
Aug 5, 2026
Merged

[FEAT] 채팅 REST 및 소켓 연동 훅 추가#65
youngmis merged 2 commits into
devfrom
feature/chat-rest-socket

Conversation

@Obebe-creator

@Obebe-creator Obebe-creator commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

📋 작업 내용

  • 채팅 기능 연동을 위한 프론트엔드 API 함수, 타입, React Query 훅, Socket.IO 채팅방 훅을 추가했습니다.

🔥 변경 사항

  • 채팅방 생성/조회 API 함수 추가
  • 채팅 메시지 목록 조회 API 함수 추가
  • 채팅 메시지 cursor pagination 타입 추가
  • 채팅 관련 query key 추가
  • 채팅방 조회 및 생성 mutation 훅 추가
  • 채팅 메시지 무한 스크롤 조회 훅 추가
  • chat:room:join, chat:message:send, chat:message:new 연동 훅 추가
  • BE 응답 계약에 맞춰 missedMessages.messages, hasMore, nextMessageId 타입 반영
  • join 실패 응답을 받을 수 있도록 chat:room:join ack callback 처리 추가
  • fetchInstance.getPaginated가 cursor pagination 타입도 받을 수 있도록 generic pagination 타입 지원

✅ 체크리스트

  • 로컬에서 정상 동작을 확인했습니다.
  • 기존 기능에 영향을 주지 않는지 확인했습니다.
  • 불필요한 console.log를 제거했습니다.
  • lint를 통과했습니다.
  • README 또는 문서를 수정했습니다. (필요 시)
  • API 명세와 일치하는지 확인했습니다.

📷 스크린샷 (선택)


🔗 관련 이슈

Closes #


💬 To Reviewer

  • 이번 PR은 채팅 UI 구현이 아니라, 채팅 기능 연동을 위한 FE 기반 작업입니다.
  • 실제 채팅방 화면, 메시지 리스트 UI, 입력창 UI는 후속 작업 범위로 분리했습니다.
  • 메시지 목록은 BE cursor pagination 응답에 맞춰 nextCursor 기반 infinite query로 조회합니다.
  • 소켓 입장 시 lastMessageId를 전달해 재연결 이후 누락 메시지를 복구할 수 있도록 구성했습니다.
  • BE 최신 응답 계약에 맞춰 missedMessages는 단순 배열이 아니라 { messages, hasMore, nextMessageId } 구조로 정의했습니다.
  • chat:room:joined 이벤트 payload와 chat:room:join ack payload 구조가 달라 타입을 분리했습니다.

Summary by CodeRabbit

  • 새 기능
    • 채팅방을 생성하고 기존 채팅방 정보를 조회할 수 있습니다.
    • 채팅 메시지를 커서 기반으로 불러오며, 이전 메시지를 추가로 확인할 수 있습니다.
    • 실시간 채팅 연결, 채팅방 입장, 신규 메시지 수신 및 메시지 전송을 지원합니다.
    • 연결 상태와 메시지 전송 오류를 확인할 수 있습니다.
    • 누락된 메시지와 채팅방 입장 결과를 처리합니다.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1af211e1-6e46-49a3-af2d-2a9a31576d4d

📥 Commits

Reviewing files that changed from the base of the PR and between 0e2cbdb and fbf5ad5.

📒 Files selected for processing (5)
  • src/hooks/useChatMessages.ts
  • src/hooks/useChatRoom.ts
  • src/hooks/useChatRoomSocket.ts
  • src/lib/api/chat.ts
  • src/lib/constants/queryKeys.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/lib/constants/queryKeys.ts
  • src/hooks/useChatRoom.ts
  • src/lib/api/chat.ts
  • src/hooks/useChatMessages.ts

📝 Walkthrough

Walkthrough

채팅 도메인 타입과 커서 페이지네이션을 추가했습니다. 채팅방·메시지 HTTP API와 인증 범위 Query Key를 연결했습니다. 조회 훅과 채팅방 소켓 참가·수신·전송 흐름을 추가했습니다.

Changes

채팅 기능

Layer / File(s) Summary
채팅 및 페이지네이션 계약
src/types/chat.ts, src/types/pagination.ts
채팅방, 메시지, payload, 소켓 ACK와 오류 타입을 추가했습니다. PaginatedApiSuccessResponse가 커스텀 페이지네이션 타입을 받도록 변경했습니다.
채팅 API 및 인증 범위 조회 키
src/lib/constants/apiRoutes.ts, src/lib/constants/queryKeys.ts, src/lib/api/chat.ts, src/lib/api/fetchInstance.ts
채팅 라우트와 인증 범위 Query Key를 추가했습니다. 채팅방 생성·조회와 커서 기반 메시지 조회 API를 구현했습니다. 공통 fetch 계층이 페이지네이션 타입을 전달하도록 변경했습니다.
채팅 조회 훅
src/hooks/useChatRoom.ts, src/hooks/useChatMessages.ts
인증 쿼리 준비 상태와 enabled 조건을 조회에 적용했습니다. useChatMessageslimit, 커서, nextCursor를 사용해 무한 조회를 구성합니다.
채팅방 소켓 흐름
src/hooks/useChatRoomSocket.ts
채팅방 참가와 신규 메시지 이벤트를 등록합니다. 현재 roomId의 이벤트만 전달합니다. 연결 끊김, ACK 타임아웃, 빈 ACK를 오류로 처리합니다.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant useChatRoomSocket
  participant SocketConnection
  participant ChatRoomServer
  useChatRoomSocket->>SocketConnection: 채팅방 참가 요청
  SocketConnection->>ChatRoomServer: roomId와 마지막 메시지 ID 전송
  ChatRoomServer-->>SocketConnection: 참가 ACK 또는 오류
  SocketConnection-->>useChatRoomSocket: 참가 결과 전달
  ChatRoomServer-->>SocketConnection: 신규 메시지 이벤트 전송
  SocketConnection-->>useChatRoomSocket: 같은 roomId의 메시지 전달
  useChatRoomSocket->>SocketConnection: 메시지 전송
  SocketConnection->>ChatRoomServer: 메시지 전송 이벤트
  ChatRoomServer-->>SocketConnection: 메시지 ACK
  SocketConnection-->>useChatRoomSocket: Promise 결과 반환
Loading

Possibly related PRs

Suggested reviewers: youngmis

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 채팅 REST API와 Socket.IO 연동 훅을 추가하는 PR의 핵심 변경을 명확하고 간결하게 설명합니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/chat-rest-socket

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/hooks/useChatRoomSocket.ts`:
- Around line 42-50: Update handleJoined in useChatRoomSocket to invoke onJoined
only when response.room.roomId matches the current roomId, mirroring the room
filter used by handleMessage. Preserve the existing joined-response handling for
the active room.
- Line 59: In src/hooks/useChatRoomSocket.ts at lines 59-59 and 76-76, store
onJoined, onMessage, and onJoinError in refs and invoke the current ref values
inside the effect handlers and join acknowledgement. Remove these consumer
callbacks from the respective dependency arrays, leaving [canConnect, roomId,
socket] at lines 59-59 and [canConnect, isConnected, roomId, socket] at lines
76-76 so listeners and room joins are not recreated on callback identity
changes.
- Around line 78-96: Update sendMessage to emit through
socket.timeout(SOCKET_ACK_TIMEOUT_MS), extracting SOCKET_ACK_TIMEOUT_MS as a
constant, and handle the timeout callback by resolving a failed ack with code
SOCKET_TIMEOUT and the payload’s clientMessageId; preserve the existing
disconnected response and successful ack behavior.

In `@src/lib/api/chat.ts`:
- Around line 22-24: Update the cursor condition in the ChatMessageListParams
query-building logic to omit only null or undefined values, while preserving
cursor=0 by setting it through searchParams.set. Keep the existing
String(cursor) conversion and request behavior for all valid numeric cursors.

In `@src/lib/constants/queryKeys.ts`:
- Around line 117-120: Update the chat query key builders ROOM, MESSAGES_ROOT,
and MESSAGES to include the authenticated user’s authScope in every key,
ensuring useChatRoom and useChatMessages do not share cached data across users.
Propagate authScope through their callers while preserving roomId and limit
distinctions.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: dec86af8-1f9a-483c-a17e-6dfccd369e11

📥 Commits

Reviewing files that changed from the base of the PR and between 587c889 and 0e2cbdb.

📒 Files selected for processing (9)
  • src/hooks/useChatMessages.ts
  • src/hooks/useChatRoom.ts
  • src/hooks/useChatRoomSocket.ts
  • src/lib/api/chat.ts
  • src/lib/api/fetchInstance.ts
  • src/lib/constants/apiRoutes.ts
  • src/lib/constants/queryKeys.ts
  • src/types/chat.ts
  • src/types/pagination.ts

Comment thread src/hooks/useChatRoomSocket.ts
Comment thread src/hooks/useChatRoomSocket.ts Outdated
Comment thread src/hooks/useChatRoomSocket.ts
Comment thread src/lib/api/chat.ts Outdated
Comment thread src/lib/constants/queryKeys.ts Outdated
@youngmis

youngmis commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

성현님, 수정이 필요한 아래 부분 모두 코드래빗 코멘트에 있어서 따로 인라인 코멘트는 달지 않도록 하겠습니다.

  1. useEffect 내 onJoined, onMessage, onJoinError 콜백 함수 의존성 배열 제외
  2. sendMessage 에서 socket.emit 호출시 pending 상태 방지를 위한 timeout 추가
  3. chat.ts 에서 커서값이 0인 경우에 대비하여 null or undefined 조건문으로 변경

@youngmis
youngmis merged commit 59048f6 into dev Aug 5, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Aug 18, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants