/
masterOK
/
FEF
Обзор
Документация
Войти
/
masterOK
/
FEF
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
useNotifications.ts
104 строки
3 KB
masterOK
upload files
10 ноя 2025, 19:52
10 ноя 2025, 19:52
2cb4a49
Код
Авторство
О чём код?
import { useEffect, useRef, useState } from "react"; import { useToast } from "@/hooks/use-toast"; import { queryClient } from "@/lib/queryClient"; export function useNotifications() { const { toast } = useToast(); const wsRef = useRef<WebSocket | null>(null); const [authToken, setAuthToken] = useState<string | null>(null); useEffect(() => { const token = localStorage.getItem("authToken"); setAuthToken(token); const interval = setInterval(() => { const currentToken = localStorage.getItem("authToken"); if (currentToken !== authToken) { setAuthToken(currentToken); } }, 1000); return () => clearInterval(interval); }, [authToken]); useEffect(() => { if (!authToken) { if (wsRef.current) { wsRef.current.close(); wsRef.current = null; } return; } const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; const host = window.location.port ? `${window.location.hostname}:${window.location.port}` : window.location.hostname; const wsUrl = `${protocol}//${host}/ws?token=${authToken}`; const ws = new WebSocket(wsUrl); wsRef.current = ws; ws.onopen = () => { console.log("Notification WebSocket connected"); }; ws.onmessage = (event) => { try { const data = JSON.parse(event.data); switch (data.type) { case "new_order": toast({ title: "Новый заказ!", description: `У вас новый заказ на сумму ${data.totalPrice} ₽`, }); queryClient.invalidateQueries({ queryKey: ["/api/orders"] }); break; case "order_status_changed": toast({ title: "Статус заказа изменен", description: `Заказ ${data.orderId.slice(0, 8)} - ${data.status}`, }); queryClient.invalidateQueries({ queryKey: [`/api/orders/${data.orderId}`] }); break; case "new_message": toast({ title: "Новое сообщение", description: data.message, }); queryClient.invalidateQueries({ queryKey: [`/api/chat/${data.orderId}`] }); break; case "new_review": toast({ title: "Новый отзыв!", description: `Вы получили отзыв с оценкой ${data.rating} звезд`, }); queryClient.invalidateQueries({ queryKey: ["/api/reviews"] }); break; } } catch (error) { console.error("WebSocket message error:", error); } }; ws.onerror = (error) => { console.error("WebSocket error:", error); }; ws.onclose = () => { console.log("WebSocket disconnected"); }; return () => { if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) { ws.close(); } }; }, [authToken, toast]); return wsRef.current; }