Monday 12 June 2017

Node.js - Listenning for database changes

I'm developing an Android application that saves information inside a smartphone database and shows closed roads using Google Maps.

Besides that, I created a server that runs Node.js to get the data from a local MySQL database and sends the data using the JSON format.

My main objective now is to listen for Server database changes and if a change was made, send a token to the Android application, requesting to update the smartphone database.

I've tried to use ZongJi and mysql-events packages but none seems to work when I make a change inside the Server database. Another option I found is to use MySQL Triggers, but since I never worked with them it's still a bit confusing to me.

This is the code I used to test the mysql-events package:

var http = require('http');
var mysql = require('mysql');
var io = require('socket.io');
var MySQLEvents = require('mysql-events');

var connection = mysql.createConnection({
        host : 'localhost',
        user : 'root',
        password : '',
        database : 'closed_roads',
});

var dsn = {
  host: 'localhost',
  user: 'root',
  password: '',
};

var mysqlEventWatcher = MySQLEvents(dsn);

var watcher = mysqlEventWatcher.add(
  'closed_roads.localizacao',
  function (oldRow, newRow, event) {
     //row inserted 
    if (oldRow === null) {
      console.log(event);
    }
 
     //row deleted 
    if (newRow === null) {
       console.log(event);
    }
 
     //row updated 
    if (oldRow !== null && newRow !== null) {
      console.log(event); 
    }
 
  }, 
  'Active'
);

var server = http.createServer(function(request, response){ 
    
        connection.query('SELECT * FROM localizacao', function(err, results, fields) {
        
                console.log('Número de Registos: ' + results.length);
                
                response.writeHead(200, { 'Content-Type': 'application/json'});
                response.end(JSON.stringify(results));
                response.end();

    });
        
}).listen(3000);

var socket = io.listen(server);

socket.on('connection', function(client){ 
    
        console.log('Ligação estabelecida com o cliente!');

    client.on('message', function(event){ 
        console.log('Mensagem recebida do cliente:', event);
    });

    client.on('disconnect',function(){
        console.log('Ligação perdida!');
    });
});

console.log('Servidor correndo em http://127.0.0.1:3000/');

I would appreciate any help to find a solution to this problem.



via Ricardo Faria

No comments:

Post a Comment