Created
June 3, 2016 17:01
-
-
Save eduardoromero/2d700b37060ed34b29bfcb6504c70867 to your computer and use it in GitHub Desktop.
NodeJS Listening to RethinkDB changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var r = require('rethinkdb'), | |
_ = require('lodash'); | |
var debug = process.env.DEBUG || false; | |
var dbConfig = { | |
host: process.env.RDB_HOST || 'localhost', | |
port: parseInt(process.env.RDB_PORT) || 28015, | |
db : process.env.RDB_DB || 'geo', | |
tables: { | |
'locations': 'id' | |
} | |
}; | |
var connection = null; | |
var connected = r.connect(dbConfig); | |
connected | |
.then(function(conn) { | |
connection = conn; | |
listen_changes(); | |
}) | |
.error(function(error) { | |
console.log(error); | |
}) | |
; | |
var listen_changes = function() { | |
r.table('locations').changes().run(connection, function(err, cursor) { | |
if (err) throw err; | |
cursor.each(function(err, row) { | |
if (err) throw err; | |
var new_pos = true; | |
var device_location = row.new_val; | |
if(!_.isUndefined(row.old_val)) { | |
new_pos = row.old_val.latitude != device_location.latitude || row.old_val.longitude != device_location.longitude | |
} | |
if(new_pos) { | |
console.log(device_location.id +': '+ device_location.protocol + | |
' lat:' + device_location.latitude + | |
' lon:' + device_location.longitude + | |
' address: ' + device_location.address | |
); | |
} | |
if(debug) { | |
console.log(JSON.stringify(row, null, 2)); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment