how to emit data from mysql server to node.js socket.io

1.4k Views Asked by At

So I've been banging my head against the wall for a bit now, I am trying to listen for events from the @rodrigogs/my-sql events node package, and emit those events through socket-io to the react client.

however there seems to be a disconnect I can't rectify between getting the data from mysql and emitting the data to the client.

const con = mysql.createConnection({
  host     : 'not local host',
  user     : 'user',
  password : 'pw',
  database : 'dbname',
  port:mysqlport
});
const myInstance = new MySQLEvents(con, {});
myInstance.start()
  .then(() => console.log('I\'m running!'))
  .catch(err => console.error('Something bad happened', err));

  myInstance.addTrigger({
    name: 'trigger1',
    expression: 'dbname.table',
    statement: MySQLEvents.STATEMENTS.ALL,
    onEvent: async (event) => {
      //socket socketio io .emit any variation of those doesn't work
        emitAnEvent(event);// current attempt      
      },

the emitAnEvent is really just, but be


function emitAnEvent(event){
   // socket is undefined, io nor socketio work.
  socketio.emit("rowUpdate",event.data)
}

I am trying this function sending idea because if I nest either of these block inside each other, terrible sadness happens, I am not sure how to access the socket outside the scope, of io.on('conneciton'...


io.on("connection", (socket) => {
    console.log("Client connected");
    
    socket.on("hydrateReq",()=>{
      console.log("hydrate request heard");
      socket.emit("hydrate", hydrateStore());
      })

    socket.emit("handshake","connected to backend");


});

and if I try to make a new connection each time there's an update... well, you can guess how well that has worked out.

so...

how do these two things work together? how do you send mysql-events through socket.io? and is there a best practice? or obviously clean way of handling this that I am missing?

I have confirmed the mysql is connected, and socket-io is connect both... and both appear to be working just fine... I'm just utterly lost on how to make these work together.



1

There are 1 best solutions below

0
On

I am blind, and could not find this anywhere in the docks, but you can access the emit through the general io from the server... defined like:

const socketio = require('socket.io');

 const io = socketio(server, {   cors: {
      origin: "*",
      methods: ["GET", "POST"],
      credentials: true
    }});



function emitAnEvent(event){
  console.log(event);//io.emit is defined and the point I was looking for...
  io.emit("rowUpdate",event)
  
}