Initial commit
This commit is contained in:
35
api/events/eventBus.ts
Normal file
35
api/events/eventBus.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type { Response } from 'express'
|
||||
import { logger } from '../utils/logger.js'
|
||||
|
||||
type NotebookEvent = {
|
||||
event: string
|
||||
path?: string
|
||||
}
|
||||
|
||||
let clients: Response[] = []
|
||||
|
||||
export const eventBus = {
|
||||
addClient: (res: Response) => {
|
||||
clients.push(res)
|
||||
logger.info(`SSE client connected. Total clients: ${clients.length}`)
|
||||
},
|
||||
removeClient: (res: Response) => {
|
||||
clients = clients.filter((c) => c !== res)
|
||||
logger.info(`SSE client disconnected. Total clients: ${clients.length}`)
|
||||
},
|
||||
broadcast: (payload: NotebookEvent) => {
|
||||
const data = `data: ${JSON.stringify(payload)}
|
||||
|
||||
`
|
||||
logger.info(`Broadcasting to ${clients.length} clients: ${payload.event} - ${payload.path || ''}`)
|
||||
clients = clients.filter((client) => {
|
||||
try {
|
||||
client.write(data)
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.warn('SSE client write failed, removing')
|
||||
return false
|
||||
}
|
||||
})
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user