refactor: isolate SSE setup

This commit is contained in:
josedario87
2025-06-09 15:16:02 -06:00
parent ed30369d3b
commit 031314d662
6 changed files with 110 additions and 5 deletions

View File

@@ -1,6 +1,7 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import { usePlanillasStore } from './stores/usePlanillas'
import App from './App.vue'
import './style.css' // Tailwind o tus estilos globales
@@ -8,12 +9,14 @@ import './style.css' // Tailwind o tus estilos globales
// console.log(`API_BASE_URL: ${API_BASE_URL}`);
const app =
createApp(App)
const app = createApp(App)
app.use(createPinia())
const pinia = createPinia()
app.use(pinia)
app.use(router)
// iniciar suscripción SSE cuando la app monte
const store = usePlanillasStore(pinia)
store.subscribeToEvents()
app.mount('#app')

View File

@@ -17,6 +17,7 @@ export const usePlanillasStore = defineStore('planillas', {
state: () => ({
planillas: [],
currentPlanilla: getDefaultCurrentPlanilla(),
_sse: null,
}),
actions: {
@@ -82,5 +83,23 @@ export const usePlanillasStore = defineStore('planillas', {
clearCurrentPlanilla() {
this.currentPlanilla = getDefaultCurrentPlanilla()
},
subscribeToEvents() {
if (this._sse) return
this._sse = new EventSource('/events')
this._sse.onmessage = (e) => {
try {
const payload = JSON.parse(e.data)
if (payload.table === 'Planilla') {
this.fetchPlanillas()
}
} catch (err) {
console.error('Error procesando SSE', err)
}
}
this._sse.onerror = () => {
console.warn('SSE connection lost, reloading...')
}
},
},
})