'nodejs websocket ws call send in controller

I'm trying to send an event if there is a request from controller.

using websocket ws:

// openWSConnection

const wsServer = new WebSocketServer({
    port: '8080'
})
const publish = (data) => {
    return data
}

const testSend = (socket) => {
     publish({}, (err,data) => {
         socket.send(data)
     })
}
wsServer.on('connection', function (socket) {
    testSend(socket)
})

module.exports = {
    publish
}

In controller

router.post("/create", async (req, res, next) => {
   openWSConnection.publish(
   {
        toUser_id,
        type,
        status,
        title,
        subtitle,
        description,
   })
})

Every time the create will triggered, Websocket are not able to send the data to the client.

I'm trying to make it work like, If there are events that is being created it will send the data to websocket and pass it to the client.

Thanks for the help!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source