B
B
BEKa T2020-12-30 19:25:43
MySQL
BEKa T, 2020-12-30 19:25:43

How to pull data from database in real time?

I need to get new entries from the database (if anything, I'm creating a web chat).
I already know about a method like:
1) you need to make a function that checks for new records from the database every second. But, I think that this method will load the server and the PC, if there is another way that will display new data at the time of its creation!
Here is my current code:
app.js

// Socket Connect
io.on('connection', function (socket) {
  console.log('Socket Run...')

  // Send sms
  socket.on('chat message', function(msg){

      let sql = `INSERT INTO myDB VALUES(${msg})`;
      db.query(sql, (err, result) => {
        if (err) throw err;
        console.log(result);
      })

    io.emit('chat message', msg);
  });

  // Disconnect
  socket.on('disconnect', function(){
    console.log('Socket STOP!');
  });
});

chat.html
$(function () {
    var socket = io();

    $('form').submit((e) => {
        e.preventDefault();
        socket.emit('chat message', $('.m').val());
        $('.m').val('');
        return false;
      });

      socket.on('chat message', function(msg){
      	$('.sms').append($('<li>').text(msg));
      });
    });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Romashkan, 2020-12-30
@Bread09

make a function that checks for new records from the database every second. But I think that this method will load the server and PC. if there is some other way that displays new data at the time of its creation.

Yes, and it's described right in your text above. Do not go to the database in a cycle, but react to messages coming through the websocket.
That is, they first wrote it to the database, then called the rest of the logic / threw an application-level event - in any way.
spoiler
Слушать изменения в БД тоже можно, конечно, например через listen/notify+процедуры в pg, но явно не нужно. Пусть логика уровня приложения остаётся на уровне приложения.

S
ski28, 2020-01-23
@ski28

I would make a different logic. What for constantly to pull mysql? Mysql should only return data once, when the page is loaded. The rest of the messages should be delivered directly to users via socket.io . And already at this stage, the data should be written in parallel to mysql.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question