fix: FRO-29 Websocket Communication (#7)
Reviewed-on: #7 Co-authored-by: Janis <janis.e.20@gmx.de> Co-committed-by: Janis <janis.e.20@gmx.de>
This commit is contained in:
55
src/composables/useWebsocket.ts
Normal file
55
src/composables/useWebsocket.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { ref, onMounted, onBeforeUnmount } from "vue";
|
||||
import {
|
||||
connectWebSocket,
|
||||
disconnectWebSocket,
|
||||
sendEvent,
|
||||
sendEventAndWait,
|
||||
onEvent,
|
||||
isWebSocketConnected,
|
||||
} from "@/services/ws";
|
||||
|
||||
export function useWebSocket() {
|
||||
const isConnected = ref(isWebSocketConnected());
|
||||
const lastMessage = ref<any>(null);
|
||||
|
||||
const lastError = ref<string | null>(null);
|
||||
|
||||
async function safeConnect(url?: string) {
|
||||
return connectWebSocket(url)
|
||||
.then(() => {
|
||||
isConnected.value = true;
|
||||
})
|
||||
.catch((err) => {
|
||||
lastError.value = err?.message ?? "Unknown WS error";
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
function useEvent<T = any>(event: string, handler: (data: T) => void) {
|
||||
const wrapped = (data: T) => {
|
||||
lastMessage.value = { event, data };
|
||||
handler(data);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
onEvent(event, wrapped);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
onEvent(event, () => {});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isConnected,
|
||||
lastMessage,
|
||||
lastError,
|
||||
|
||||
connect: safeConnect,
|
||||
disconnect: disconnectWebSocket,
|
||||
send: sendEvent,
|
||||
sendAndWait: sendEventAndWait,
|
||||
|
||||
useEvent,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user