1

how to implement SSE in adonisjs

I have an application and I'm having trouble implementing Server Sent Events (SSE) in AdonisJs. I can initiate the connection and send messages, but I don't know where and how to store the list of connected users. I tried to store using Redis, but when saving the request response, the error "TypeError: Converting circular structure to JSON in nodejs" occurs when trying to Stringify the response object through the JSON.stringify method. Before you ask me, I'm storing the response of the request (in a list of clients [] ) for later in any other Controller to send a message for the connection of all connected clients. Code below:

/routes.ts

Route.get('/stream', ({ request, response,  }) => { 
  sseFn(request, response, 'connect')
})

Route.post('/stream-new-event', ({ request, response }) => {
  sseFn(request, response, 'newEvent')
})

/utils/sendEvent.ts

const clients = [] as any

const sseFn = (response, request, type: string) => {
  if (type === 'connect') {
    const headers = {
      'Content-Type': 'text/event-stream',
      'Connection': 'keep-alive',
      'Cache-Control': 'no-cache',
      'access-control-allow-origin': '*',
    }
    response.response.writeHead(200, headers)
    response.response.write(`data: ${JSON.stringify({ message: "Welcome"})}\n\n`)
    clients.push({response: response.response })

  } else {
    clients.forEach((client) => {
      client.response.write(`data: ${JSON.stringify({ message: 'New user' })}\n\n`)
    })
  }
}

export { sseFn }

Is this a viable method for using SSE?

Can I store connected clients in a loose list in AdonisJS? I know using cache would be a better option, but I'm getting the error "TypeError: Converting circular structure to JSON in nodejs" when storing in Redis.

  • Did you figure this out? I'm not sure how I'm supposed store the connections either. But I'm pretty sure you can stringify them and store them in redis? Did you end up doing that? – Amon Dec 25 '22 at 02:45

0 Answers0