spencerlambert / mysql-events

A node meteor package that watches a MySQL database and runs callbacks on matched events.
Other
87 stars 76 forks source link

Update:

I haven't been activly updating this code. Others have been activley making updates. Please also checkout their work.

https://github.com/rodrigogs/mysql-events

Note: This version doesn't follow my documentation, so please reference the supplied example code for setup.

https://github.com/rodrigogs/mysql-events/blob/master/examples/watchWholeInstance.js

mysql-events

A Node JS NPM package that watches a MySQL database and runs callbacks on matched events.

This package is based on the ZongJi node module. Please make sure that you meet the requirements described at ZongJi, like MySQL binlog etc.

Quick Start

var MySQLEvents = require('mysql-events');
var dsn = {
  host:     _dbhostname_,
  user:     _dbusername_,
  password: _dbpassword_,
};
var mysqlEventWatcher = MySQLEvents(dsn);
var watcher =mysqlEventWatcher.add(
  'myDB.table.field.value',
  function (oldRow, newRow, event) {
     //row inserted
    if (oldRow === null) {
      //insert code goes here
    }

     //row deleted
    if (newRow === null) {
      //delete code goes here
    }

     //row updated
    if (oldRow !== null && newRow !== null) {
      //update code goes here
    }

    //detailed event information
    //console.log(event)
  }, 
  'match this string or regex'
);

Installation

npm install mysql-events

Usage

Make sure the database user has the privilege to read the binlog on database that you want to watch on.

This will listen to any change in the fieldName and if the changed value is equal to Active, then triggers the callback. Passing it 2 arguments. Argument value depends on the event.

rowObject

It has the following structure:

{
  database: dbName,
  table: tableName,
  affectedColumns: {
    [{
      name:     fieldName1,
      charset:  String,
      type:     Number
      metedata: String
    },{
      name:     fieldName2,
      charset:  String,
      type:     Number
      metedata: String
    }]
},{
  changedColumns: [fieldName1, fieldName2],
  fields: {
   fieldName1: recordValue1,
   fieldName2: recordValue2,
     ....
     ....
     ....
   fieldNameN: recordValueN
  }
}

Remove an event

event1.remove();

Stop all events on the connection

myCon.stop();

Additional options

In order to customize the connection options, you can provide your own settings passing a second argument object to the connection function.

var mysqlEventWatcher = MySQLEvents(dsn, {
  startAtEnd: false // it overrides default value "true"
});

You can find the list of the available options here.

Watcher Setup

Its basically a dot '.' seperated string. It can have the following combinations

LICENSE

MIT