Create a notification server using MySql/ Node js

后端 未结 1 1000
后悔当初
后悔当初 2021-01-28 14:59

I am working on a project where I should post notification whenever an database event is fired.

I am using NODE for this. BUt I am not sure whether I\'ll be able to do i

相关标签:
1条回答
  • 2021-01-28 15:36

    As for as I know, there isn't any simple way to read database triggers in Node, so a common solution is to use Redis as a publish system, and have a connector module perferm the actual database query. A very popular MySQL connector for Node is this one, so I will be using it as an example.

    When using a module, the "MySQL triggers" you're looking for are just simple callbacks that you would find with most asynchronous modules. Here's an example of a query with the node-mysql module:

    var post  = {id: 1, title: 'Hello MySQL'};
    connection.query('INSERT INTO posts SET ?', post, function(err, result) {
      //the database transaction has completed, notify the client
    });
    

    When the callback is called, that means the database operation has either completed, or failed (check the err property in the callback to check this). You could then send this change to a browser using EventSource/Server-Sent Events or WebSockets.

    As a side answer to your third question, pushing data from the server to client will always be more efficient than the client consistently asking for data, because the server is not guaranteed to have need data when the client has asked for it.

    0 讨论(0)
提交回复
热议问题