Files
chore/frontend/vue-app/src/common/backendEvents.ts
Ryan Kegel 8cb9199ab7
Some checks failed
Chore App Build, Test, and Push Docker Images / build-and-push (push) Has been cancelled
Releasing 1.0.4 into test
2026-02-19 15:13:08 -05:00

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()
})
}