Some checks failed
Chore App Build, Test, and Push Docker Images / build-and-push (push) Has been cancelled
29 lines
761 B
TypeScript
29 lines
761 B
TypeScript
import { onMounted, onBeforeUnmount, watch } from 'vue'
|
|
import type { Ref } from 'vue'
|
|
import { eventBus } from './eventBus'
|
|
|
|
export function useBackendEvents(userId: Ref<string>) {
|
|
let eventSource: EventSource | null = null
|
|
|
|
const connect = () => {
|
|
if (eventSource) eventSource.close()
|
|
if (userId.value) {
|
|
eventSource = new EventSource(`/events?user_id=${userId.value}`)
|
|
|
|
eventSource.onmessage = (event) => {
|
|
const data = JSON.parse(event.data)
|
|
|
|
// Emit globally for any component that cares
|
|
eventBus.emit(data.type, data)
|
|
eventBus.emit('sse', data) // optional: catch-all channel
|
|
}
|
|
}
|
|
}
|
|
|
|
onMounted(connect)
|
|
watch(userId, connect)
|
|
onBeforeUnmount(() => {
|
|
eventSource?.close()
|
|
})
|
|
}
|