Skip to content

Commit

Permalink
fix: Fix sending real-time updates.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahmoud-Emad committed Oct 21, 2024
1 parent 95157fa commit 05154d2
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 75 deletions.
74 changes: 7 additions & 67 deletions client/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,92 +6,32 @@

<script lang="ts">
import { defineComponent, onMounted } from 'vue'
import { useNotifier } from 'vue3-notifier'
import { useApi } from '@/hooks'
import SideDrawer from './components/SideDrawer.vue'
import { useWSConnectionStore } from './stores/WSConnection'
import { useNotificationStore } from './stores/notifications'
import type { notificationType, WSErrorType } from './types'
import { useHomeEventsStore } from './stores/homeEvents'
export default defineComponent({
name: 'App',
components: {
SideDrawer
},
setup() {
const api = useApi()
const notifier = useNotifier()
if (api && notifier) {
notifier.notify
api.setNotifier(notifier)
}
const WSConnection = useWSConnectionStore()
const notifications = useNotificationStore()
const connection = WSConnection.connect()
const handleIncomingMessage = (event: MessageEvent) => {
const data: notificationType | WSErrorType = JSON.parse(event.data as string);
if ('code' in data && 'message' in data) {
// Handle error
const error: WSErrorType = data as WSErrorType;
const noti = notifier.notify({
title: 'An error received from the WebSocket',
description: error.message,
type: 'error'
});
setTimeout(() => {
noti?.destroy();
}, 4000);
} else {
// Handle notification
const notification: notificationType = data as notificationType;
const homeEventsStore = useHomeEventsStore();
notifications.addNotification(notification);
if (notification.request.type === "vacation") {
homeEventsStore.reload = true;
}
const noti = notifier.notify({
title: notification.title,
description: notification.body,
type: 'success'
});
setTimeout(() => {
noti?.destroy();
}, 4000);
}
};
onMounted(async () => {
window.connections = {
ws: connection
}
if (window.connections.ws.value) {
window.connections.ws.value!.onmessage = (event: MessageEvent) =>
handleIncomingMessage(event)
window.connections.ws.value!.onerror = (error) => {
console.error('WebSocket error:', error)
}
window.connections.ws.value!.onclose = (event) => {
console.log('WebSocket connection closed:', event)
onMounted(async () => {
window.connections = {
ws: connection
}
}
})
}
WSConnection.WSHandleConnection();
})
}
})
</script>
<style>
.vue3-notifier-container .text-error {
background-color: rgb(44, 16, 16) !important;
}
.vue3-notifier-container .text-success {
background-color: rgb(2, 29, 3) !important;
}
Expand Down
85 changes: 79 additions & 6 deletions client/src/stores/WSConnection.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,99 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ref, type Ref } from 'vue';
import { ApiClientBase } from "@/clients/api/base";
import { useAsyncState } from '@vueuse/core';
import { $api } from '@/clients';
import { useNotificationStore } from './notifications';
import { useNotifier } from 'vue3-notifier';
import type { notificationType, WSErrorType } from '@/types';
import { useHomeEventsStore } from './homeEvents';
import { useApi } from '@/hooks';

// Define the store
export const useWSConnectionStore = defineStore('WSConnectionStore', () => {
const me = ApiClientBase.user.value?.fullUser;
const WSConnection = ref<WebSocket | null>(null);

// Initialize notifier and api inside the store
const notifier = useNotifier();
const api = useApi();

if (api && notifier) {
notifier.notify;
api.setNotifier(notifier);
}

// Actions
const connect = () => {
const connect = (): Ref<WebSocket | null> => {
if (me) {
WSConnection.value = new WebSocket(`${window.env.SERVER_DOMAIN_NAME_WS}/${me.id}/?token=Bearer ` + localStorage.getItem("USER_ACCESS_KEY"));
}
return WSConnection;
};

const reconnect = () => {
return connect()
}
const reconnect = async (): Promise<Ref<WebSocket | null>> => {
const user = await useAsyncState(() => $api.myprofile.getUser(), null).execute();
if (user) {
WSConnection.value = new WebSocket(`${window.env.SERVER_DOMAIN_NAME_WS}/${user.id}/?token=Bearer ` + localStorage.getItem("USER_ACCESS_KEY"));
}
return WSConnection;
};

const handleIncomingMessage = (event: MessageEvent) => {
const notifications = useNotificationStore();
const data: notificationType | WSErrorType = JSON.parse(event.data as string);

if ('code' in data && 'message' in data) {
// Handle error
const error: WSErrorType = data as WSErrorType;
console.error('Error received from the WebSocket:', error);
// const noti = notifier.notify({
// title: 'An error received from the WebSocket',
// description: error.message,
// type: 'error',
// });

// setTimeout(() => {
// noti?.destroy();
// }, 4000);
} else {
// Handle notification
const notification: notificationType = data as notificationType;
const homeEventsStore = useHomeEventsStore();
notifications.addNotification(notification);

if (notification.request.type === "vacation") {
homeEventsStore.reload = true;
}

const noti = notifier.notify({
title: notification.title,
description: notification.body,
type: 'success',
});

setTimeout(() => {
noti?.destroy();
}, 4000);
}
};

const WSHandleConnection = () => {
if (window.connections.ws.value) {
window.connections.ws.value!.onmessage = (event: MessageEvent) =>
handleIncomingMessage(event);
window.connections.ws.value!.onerror = (error) => {
console.error('WebSocket error:', error);
};
window.connections.ws.value!.onclose = (event) => {
console.log('WebSocket connection closed:', event);
};
}
};

return {
connect,
reconnect
reconnect,
WSHandleConnection,
};
});
5 changes: 3 additions & 2 deletions client/src/views/LoginView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ export default defineComponent({
null,
{
immediate: false,
onSuccess: () => {
WSConnection.reconnect();
onSuccess: async () => {
window.connections.ws = await WSConnection.reconnect();
WSConnection.WSHandleConnection();
return router.push('/');
}
}
Expand Down

0 comments on commit 05154d2

Please sign in to comment.