codex-ai-platform / src /hooks /useSocket.ts
3v324v23's picture
feat:让打包的 App 可以访问线上数据
e4b7d6f
import { useEffect, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import { useStore } from '@/store/useStore';
import { getBaseUrl } from '@/lib/api';
export const useSocket = () => {
const { user, token } = useStore();
const socketRef = useRef<Socket | null>(null);
useEffect(() => {
if (!token || !user) return;
// 初始化连接,增加鉴权
const baseUrl = getBaseUrl();
const socket = io(baseUrl || window.location.origin, {
auth: { token }
});
socketRef.current = socket;
socket.on('connect', () => {
console.log('[Socket] 已认证连接');
});
// 监听全局事件 (例如管理员广播)
if (user.role === 'admin') {
socket.on('admin:circuit_breaker_change', (data) => {
console.warn('[Socket] 熔断器状态变更:', data);
// 这里可以触发一个全局 Toast
});
}
return () => {
socket.disconnect();
};
}, [token, user]);
return socketRef.current;
};