feat:Websocket服务拆到单独服务,主后台保持单工通信

This commit is contained in:
zpaeng
2025-09-02 23:10:29 +08:00
parent 575e90e558
commit 84236b0174
35 changed files with 1504 additions and 329 deletions

View File

@@ -3,82 +3,73 @@ import { useWebSocket } from './useWebSocket'
import { getToken } from '~/utils/auth'
const count = ref(0)
let isInitialized = false
let wsSubscription = null
let isInitialized = false;
export function useChannelsUnreadCount() {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const { subscribe, isConnected, connect } = useWebSocket()
const config = useRuntimeConfig();
const API_BASE_URL = config.public.apiBaseUrl;
const { subscribe, isConnected, connect } = useWebSocket();
const fetchChannelUnread = async () => {
const token = getToken()
const token = getToken();
if (!token) {
count.value = 0
return
count.value = 0;
return;
}
try {
const response = await fetch(`${API_BASE_URL}/api/channels/unread-count`, {
headers: { Authorization: `Bearer ${token}` },
})
});
if (response.ok) {
const data = await response.json()
count.value = data
const data = await response.json();
count.value = data;
}
} catch (e) {
console.error('Failed to fetch channel unread count:', e)
console.error('Failed to fetch channel unread count:', e);
}
}
};
const setupWebSocketListener = () => {
const destination = '/user/queue/channel-unread';
subscribe(destination, (message) => {
const unread = parseInt(message.body, 10);
if (!isNaN(unread)) {
count.value = unread;
}
}).then(subscription => {
if (subscription) {
console.log('频道未读消息订阅成功');
}
});
};
const initialize = () => {
const token = getToken()
const token = getToken();
if (!token) {
count.value = 0
return
count.value = 0;
return;
}
fetchChannelUnread()
if (!isConnected.value) {
connect(token)
}
setupWebSocketListener()
}
const setupWebSocketListener = () => {
if (!wsSubscription) {
watch(
isConnected,
(newValue) => {
if (newValue && !wsSubscription) {
wsSubscription = subscribe('/user/queue/channel-unread', (message) => {
const unread = parseInt(message.body, 10)
if (!isNaN(unread)) {
count.value = unread
}
})
}
},
{ immediate: true },
)
if (!isConnected.value) {
connect(token);
}
}
fetchChannelUnread();
setupWebSocketListener();
};
const setFromList = (channels) => {
count.value = Array.isArray(channels) ? channels.filter((c) => c.unreadCount > 0).length : 0
}
count.value = Array.isArray(channels) ? channels.filter((c) => c.unreadCount > 0).length : 0;
};
const hasUnread = computed(() => count.value > 0)
const hasUnread = computed(() => count.value > 0);
const token = getToken()
if (token) {
if (!isInitialized) {
isInitialized = true
initialize()
} else {
fetchChannelUnread()
if (!isConnected.value) {
connect(token)
}
setupWebSocketListener()
if (!isInitialized) {
const token = getToken();
if (token) {
isInitialized = true;
initialize();
}
}
@@ -88,5 +79,5 @@ export function useChannelsUnreadCount() {
fetchChannelUnread,
initialize,
setFromList,
}
};
}