added refresh token
This commit is contained in:
@@ -4,6 +4,7 @@ import SockJS from "sockjs-client";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
import { useUnread } from "../context/UnreadContext";
|
||||
import { getActiveChatId } from "../stores/activeChatStore";
|
||||
import { getAccessToken, refreshAccessToken } from "../api/apiClient";
|
||||
|
||||
export function useUnreadSocket(userId) {
|
||||
const { setChatUnread } = useUnread();
|
||||
@@ -12,12 +13,14 @@ export function useUnreadSocket(userId) {
|
||||
useEffect(() => {
|
||||
if (!userId) return;
|
||||
|
||||
const token = localStorage.getItem("token");
|
||||
const socket = new SockJS(`${API_URL}/ws?token=${token}`);
|
||||
|
||||
const client = new Client({
|
||||
webSocketFactory: () => socket,
|
||||
webSocketFactory: () => new SockJS(`${API_URL}/ws`),
|
||||
reconnectDelay: 3000,
|
||||
beforeConnect: () => {
|
||||
client.connectHeaders = {
|
||||
Authorization: `Bearer ${getAccessToken()}`,
|
||||
};
|
||||
},
|
||||
onConnect: () => {
|
||||
client.subscribe(`/topic/user/${userId}/unread`, (msg) => {
|
||||
const body = JSON.parse(msg.body);
|
||||
@@ -25,6 +28,15 @@ export function useUnreadSocket(userId) {
|
||||
setChatUnread(body.chatId, body.unreadCount);
|
||||
});
|
||||
},
|
||||
onStompError: async (frame) => {
|
||||
if (frame.headers?.message?.includes("Unauthorized")) {
|
||||
try {
|
||||
await refreshAccessToken();
|
||||
} catch {
|
||||
// refresh не удался — общий логин-флоу разберётся при следующем apiFetch
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
client.activate();
|
||||
@@ -32,4 +44,4 @@ export function useUnreadSocket(userId) {
|
||||
|
||||
return () => client.deactivate();
|
||||
}, [userId, setChatUnread]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user