This commit is contained in:
2025-12-03 17:40:50 +03:00
parent d3d8b7522a
commit 4cad91440c
34 changed files with 1120 additions and 434 deletions

104
src/stores/SSE.ts Normal file
View File

@@ -0,0 +1,104 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from 'boot/axios'
import { useProjectsStore } from 'stores/projects'
import { useChatsStore } from 'stores/chats'
import { useUsersStore } from 'stores/users'
export const useSSEStore = defineStore('sse', () => {
const eventSource = ref<EventSource | null>(null)
const isConnected = ref(false)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5
const projectsStore = useProjectsStore()
const chatsStore = useChatsStore()
const usersStore = useUsersStore()
const currentProjectId = computed(() => projectsStore.currentProjectId)
const connect = () => {
try {
if (eventSource.value) eventSource.value.close()
const url = api.defaults.baseURL + '/events'
eventSource.value = new EventSource(url)
setupEventListeners()
eventSource.value.onopen = () => {
isConnected.value = true
reconnectAttempts.value = 0
console.log('SSE connected')
}
eventSource.value.onerror = (error) => {
console.error('SSE error:', error)
isConnected.value = false
if (reconnectAttempts.value < maxReconnectAttempts) {
setTimeout(() => {
reconnectAttempts.value++
connect()
}, 3000 * reconnectAttempts.value)
}
}
} catch (error) {
console.error('Failed to connect SSE:', error)
}
}
const disconnect = () => {
if (eventSource.value) {
eventSource.value.close()
eventSource.value = null
}
isConnected.value = false
reconnectAttempts.value = 0
}
const setupEventListeners = () => {
if (!eventSource.value) return
eventSource.value.addEventListener('chat-attach', (event) => {
const data = JSON.parse(event.data)
if (data.project_id === currentProjectId.value) {
chatsStore.init().catch(() => {})
}
})
eventSource.value.addEventListener('chat-delete', (event) => {
const data = JSON.parse(event.data)
if (data.project_id === currentProjectId.value) {
chatsStore.init().catch(() => {})
usersStore.init().catch(() => {})
}
})
eventSource.value.addEventListener('chat-detach', (event) => {
const data = JSON.parse(event.data)
if (data.project_id === currentProjectId.value) {
chatsStore.detach(data.id)
usersStore.init().catch(() => {})
}
})
eventSource.value.addEventListener('chat-update', (event) => {
const data = JSON.parse(event.data)
if (data.project_id === currentProjectId.value) {
chatsStore.init().catch(() => {})
}
})
}
const eventSourceComputed = computed(() => eventSource.value)
const isConnectedComputed = computed(() => isConnected.value)
return {
eventSource: eventSourceComputed,
isConnected: isConnectedComputed,
connect,
disconnect
}
})