Skip to content

Commit 32fe647

Browse files
Make socket more stable
1 parent 3486025 commit 32fe647

4 files changed

Lines changed: 75 additions & 50 deletions

File tree

src/frontend/src/components/chat-detail-component.vue

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,10 @@ const loadChat = async () => {
6363
// Try to initialize socket connection for real-time updates
6464
try {
6565
await sockets.hub.initialize();
66-
sockets.hub.joinChat(chatId);
67-
sockets.hub.registerToEvent('ReceiveMessage', handleIncomingMessage);
68-
sockets.hub.registerToEvent('UpdateMessage', handleMessageUpdate);
69-
sockets.hub.registerToEvent('DeleteMessage', handleMessageDelete);
66+
await sockets.hub.joinChat(chatId);
67+
await sockets.hub.registerToEvent('ReceiveMessage', handleIncomingMessage);
68+
await sockets.hub.registerToEvent('UpdateMessage', handleMessageUpdate);
69+
await sockets.hub.registerToEvent('DeleteMessage', handleMessageDelete);
7070
isSocketConnected.value = true;
7171
} catch (socketError) {
7272
console.warn('Failed to connect to real-time messaging. Messages will not update automatically:', socketError);
@@ -322,10 +322,10 @@ onMounted(() => {
322322
loadChat();
323323
});
324324
325-
onUnmounted(() => {
325+
onUnmounted(async () => {
326326
if (chat.value && isSocketConnected.value) {
327327
try {
328-
sockets.hub.leaveChat(chat.value.uid);
328+
await sockets.hub.leaveChat(chat.value.uid);
329329
} catch (error) {
330330
console.warn('Error leaving chat:', error);
331331
}

src/frontend/src/components/chats-list-component.vue

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,6 @@ const loadUnreadCounts = async () => {
132132
})
133133
);
134134
unreadCounts.value = counts;
135-
console.log('Loaded unread counts:', counts);
136135
} catch (error) {
137136
console.error('Error loading unread counts:', error);
138137
}
@@ -210,8 +209,8 @@ onMounted(async () => {
210209
await loadChats();
211210
try {
212211
await sockets.hub.initialize();
213-
sockets.hub.registerToEvent('NewUnreadChatMessage', handleUnreadMessageUpdate);
214-
sockets.hub.joinMessaging();
212+
await sockets.hub.registerToEvent('NewUnreadChatMessage', handleUnreadMessageUpdate);
213+
await sockets.hub.joinMessaging();
215214
isSocketConnected.value = true;
216215
} catch (error) {
217216
console.warn('Failed to connect to real-time messaging. Badge counts will not update automatically:', error);

src/frontend/src/layout/layout-component.vue

Lines changed: 58 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<script setup lang="ts">
2-
import { onUnmounted, ref, watch } from "vue";
2+
import { computed, watch, onMounted, ref } from "vue";
33
import { useAuthStore } from "../stores/auth-store";
44
import NavbarComponent from "./navbar-component.vue";
55
import { services, sockets } from "../services/api";
@@ -8,50 +8,71 @@ const authStore = useAuthStore();
88
99
const totalUnreadMessages = ref(0);
1010
const isSocketConnected = ref(false);
11+
const isAuthenticated = computed(() => authStore.isAuthenticated.value && !!authStore.userId.value);
1112
12-
watch(authStore.isAuthenticated, async (_) => {
13-
if (authStore.isAuthenticated) {
14-
try {
15-
await sockets.hub.initialize();
16-
sockets.hub.registerToEvent("NewTotalUnreadChatMessage",
17-
(newTotal: number) => {
18-
totalUnreadMessages.value = newTotal;
19-
});
20-
sockets.hub.joinMessaging();
21-
isSocketConnected.value = true;
22-
} catch (error) {
23-
console.warn('Failed to connect to real-time messaging:', error);
24-
isSocketConnected.value = false;
25-
}
26-
27-
const userId = authStore.userId;
28-
await checkUnreadMessages(userId.value!);
29-
}
30-
}, {immediate: true});
13+
const initSocket = async () => {
14+
if (isSocketConnected.value) return;
15+
16+
try {
17+
await sockets.hub.initialize();
18+
19+
await sockets.hub.registerToEvent("NewTotalUnreadChatMessage", (newTotal: number) => {
20+
totalUnreadMessages.value = newTotal;
21+
});
22+
23+
await sockets.hub.joinMessaging();
24+
isSocketConnected.value = true;
25+
26+
const userId = authStore.userId;
27+
if (userId?.value) await checkUnreadMessages(userId.value);
28+
} catch (error) {
29+
console.warn("Failed to connect to real-time messaging:", error);
30+
isSocketConnected.value = false;
31+
}
32+
};
3133
3234
const checkUnreadMessages = async (userId: string) => {
33-
try {
34-
const res = await services.userChatMessageStatus.getTotalUnreadMessages(userId);
35-
if (res.isSuccess && res.data) {
36-
totalUnreadMessages.value = res.data.countUnreadMessages;
37-
}
38-
} catch (error) {
39-
console.warn('Failed to fetch unread message count:', error);
35+
try {
36+
const res = await services.userChatMessageStatus.getTotalUnreadMessages(userId);
37+
if (res.isSuccess && res.data) {
38+
totalUnreadMessages.value = res.data.countUnreadMessages;
4039
}
41-
}
40+
} catch (error) {
41+
console.warn("Failed to fetch unread message count:", error);
42+
}
43+
};
4244
45+
const cleanupSocket = async () => {
46+
if (!isSocketConnected.value) return;
47+
try {
48+
await sockets.hub.leaveMessaging();
49+
} catch (e) {
50+
console.warn("Error leaving messaging:", e);
51+
} finally {
52+
sockets.hub.flush();
53+
isSocketConnected.value = false;
54+
}
55+
};
4356
44-
window.addEventListener('beforeunload', () => {
45-
if (isSocketConnected.value) {
46-
sockets.hub.leaveMessaging();
57+
watch(
58+
isAuthenticated,
59+
async (newVal, oldVal) => {
60+
if (newVal && !oldVal) {
61+
await initSocket();
62+
} else if (!newVal && oldVal) {
63+
await cleanupSocket();
4764
}
48-
})
65+
},
66+
{ immediate: false }
67+
);
4968
50-
onUnmounted(() => {
51-
if (isSocketConnected.value) {
52-
sockets.hub.leaveMessaging();
53-
}
54-
})
69+
onMounted(async () => {
70+
if (isAuthenticated.value) {
71+
await initSocket();
72+
}
73+
});
74+
75+
window.addEventListener("beforeunload", cleanupSocket);
5576
</script>
5677

5778
<template>

src/frontend/src/services/api/index.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,26 +51,31 @@ export const sockets = {
5151
* @param action Function which is executed when the event is triggered over the socket
5252
*/
5353
registerToEvent: async(event: string, action: Function) => {
54+
await initPromise;
5455
socketBaseClient.registerToEvent(event, action);
5556
},
5657
/**
5758
* Send a JoinChat event over the socket to the backend
5859
* @param chatId Guid (string) with the chatId
5960
*/
60-
joinChat: (chatId: string) => {
61+
joinChat: async (chatId: string) => {
62+
await initPromise;
6163
socketBaseClient.sendEvent("JoinChat", [chatId]);
6264
},
6365
/**
6466
* Send a LeaveChat event over the socket to the backend to unsubscribe to chat messages
6567
* @param chatId Guid (string) with the chatId to be left
6668
*/
67-
leaveChat: (chatId: string) => {
69+
leaveChat: async (chatId: string) => {
70+
await initPromise;
6871
socketBaseClient.sendEvent("LeaveChat", [chatId]);
6972
},
70-
joinMessaging: () => {
73+
joinMessaging: async () => {
74+
await initPromise;
7175
socketBaseClient.sendEvent("JoinMessaging", []);
7276
},
73-
leaveMessaging: () => {
77+
leaveMessaging: async () => {
78+
await initPromise;
7479
socketBaseClient.sendEvent("LeaveMessaging", []);
7580
}
7681
}

0 commit comments

Comments
 (0)