added refresh token

This commit is contained in:
SlimusMinus
2026-08-03 02:44:57 +03:00
parent b6c61c72d9
commit abbcc330e7
16 changed files with 210 additions and 135 deletions

View File

@@ -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]);
}
}