-
Notifications
You must be signed in to change notification settings - Fork 1
[Refactor] 알림 SSE 훅 구조 개선 및 타입 단순화 #391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 3 commits
5a07052
4854e4c
9747281
5fe306d
822081e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export { useSSEConnect } from './use-sse-connect'; | ||
| export { useSSEEvent } from './use-sse-event'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import { useEffect, useRef, useState } from 'react'; | ||
|
|
||
| import Cookies from 'js-cookie'; | ||
|
|
||
| import { API } from '@/api'; | ||
| import { NotificationItem } from '@/types/service/notification'; | ||
|
|
||
| export const useSSEConnect = () => { | ||
| const [data, setData] = useState<NotificationItem | null>(null); | ||
|
|
||
| const eventSourceRef = useRef<EventSource | null>(null); | ||
| const retryRefreshRef = useRef(false); | ||
|
|
||
| // SSE 연결 진입점 | ||
| const connect = () => { | ||
| const token = Cookies.get('accessToken'); | ||
| if (!token) { | ||
| console.log('[DEBUG] SSE - 토큰 없음'); | ||
| return; | ||
| } | ||
|
|
||
| setupSSEConnection(token); | ||
| }; | ||
|
|
||
| // SSE 연결 해제 함수 | ||
| const disconnect = () => { | ||
| if (eventSourceRef.current) { | ||
| console.log('[DEBUG] SSE - 연결 정리'); | ||
| eventSourceRef.current.close(); | ||
| eventSourceRef.current = null; | ||
| } | ||
| retryRefreshRef.current = false; | ||
| }; | ||
|
|
||
| // SSE 재연결 시도 함수 | ||
| const reconnect = async () => { | ||
| retryRefreshRef.current = true; | ||
| console.log('[DEBUG] SSE - 토큰 갱신 시도'); | ||
|
|
||
| try { | ||
| await API.authService.refresh(); | ||
| const token = Cookies.get('accessToken'); | ||
| if (token) { | ||
| setupSSEConnection(token); | ||
| } | ||
| } catch (error) { | ||
| console.error('[DEBUG] SSE - 토큰 갱신 실패:', error); | ||
| disconnect(); | ||
| } | ||
| }; | ||
|
|
||
| // SSE 연결 설정 함수 | ||
| const setupSSEConnection = (token: string) => { | ||
| // 1. 기존 연결 정리 | ||
| if (eventSourceRef.current) { | ||
| console.log('[DEBUG] SSE - 기존 연결 정리'); | ||
| eventSourceRef.current.close(); | ||
| eventSourceRef.current = null; | ||
| } | ||
|
|
||
| // 2. SSE 연결 시도 | ||
| console.log('[DEBUG] SSE - 연결 시도'); | ||
| const es = new EventSource( | ||
| `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/notifications/subscribe?accessToken=${token}`, | ||
| ); | ||
|
Comment on lines
+69
to
+71
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🌐 Web query:
💡 Result: Does the browser
|
||
|
|
||
| eventSourceRef.current = es; | ||
|
|
||
| // 3. SSE 연결 성공 시 | ||
| es.addEventListener('connect', (event) => { | ||
| console.log('[DEBUG] SSE - 연결 확인:', event.data); | ||
| retryRefreshRef.current = false; | ||
| }); | ||
|
|
||
| // 4. SSE 이벤트 수신 시 | ||
| es.addEventListener('notification', (event) => { | ||
| try { | ||
| const receivedData = JSON.parse(event.data) as NotificationItem; | ||
| setData(receivedData); | ||
| console.log('[DEBUG] SSE - 수신 성공:', receivedData); | ||
| } catch (error) { | ||
| console.error('[DEBUG] SSE - 데이터 파싱 실패:', error); | ||
| } | ||
| }); | ||
|
|
||
| // 5. SSE 연결 오류 발생 시 | ||
| es.onerror = async (_error) => { | ||
| console.log('[DEBUG] SSE - 연결 오류 발생'); | ||
| es.close(); | ||
| reconnect(); | ||
| }; | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }; | ||
|
|
||
| useEffect(() => { | ||
| connect(); | ||
| return () => disconnect(); | ||
| }, []); | ||
|
|
||
| // 알림 수신 후 3초 뒤 data가 null로 변경됨 | ||
| useEffect(() => { | ||
| if (!data) return; | ||
|
|
||
| const timer = setTimeout(() => { | ||
| setData(null); | ||
| }, 3000); | ||
|
|
||
| return () => clearTimeout(timer); | ||
| }, [data]); | ||
|
|
||
| return { data }; | ||
| }; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { useEffect } from 'react'; | ||
|
|
||
| import { QueryKey, useQueryClient } from '@tanstack/react-query'; | ||
|
|
||
| import { groupKeys } from '@/lib/query-key/query-key-group'; | ||
| import { notificationKeys } from '@/lib/query-key/query-key-notification'; | ||
| import { userKeys } from '@/lib/query-key/query-key-user'; | ||
| import { NotificationItem } from '@/types/service/notification'; | ||
|
|
||
| const SSE_INVALIDATION_MAP: Partial< | ||
| Record<NotificationItem['type'], (data: NotificationItem) => QueryKey[]> | ||
| > = { | ||
| FOLLOW: (data) => [userKeys.me(), userKeys.item(data.user.id)], | ||
| GROUP_CREATE: () => [groupKeys.lists()], | ||
| GROUP_DELETE: () => [groupKeys.lists()], | ||
| GROUP_JOIN: (data) => (data.group ? [groupKeys.detail(String(data.group.id))] : []), | ||
| GROUP_LEAVE: (data) => (data.group ? [groupKeys.detail(String(data.group.id))] : []), | ||
| GROUP_JOIN_APPROVED: (data) => (data.group ? [groupKeys.detail(String(data.group.id))] : []), | ||
| GROUP_JOIN_REJECTED: (data) => (data.group ? [groupKeys.detail(String(data.group.id))] : []), | ||
| GROUP_JOIN_KICKED: (data) => (data.group ? [groupKeys.detail(String(data.group.id))] : []), | ||
| GROUP_JOIN_REQUEST: (data) => | ||
| data.group ? [groupKeys.joinRequests(String(data.group.id), 'PENDING')] : [], | ||
| }; | ||
|
|
||
| export const useSSEEvent = (data: NotificationItem | null) => { | ||
| const queryClient = useQueryClient(); | ||
|
|
||
| useEffect(() => { | ||
| if (!data) return; | ||
| queryClient.invalidateQueries({ queryKey: notificationKeys.unReadCount() }); | ||
| queryClient.invalidateQueries({ queryKey: notificationKeys.list() }); | ||
|
|
||
| const getQueryKeys = SSE_INVALIDATION_MAP[data.type]; | ||
| getQueryKeys?.(data).forEach((queryKey) => { | ||
| queryClient.invalidateQueries({ queryKey }); | ||
| }); | ||
| }, [data]); | ||
| }; |
Uh oh!
There was an error while loading. Please reload this page.