Guest User

Untitled

a guest
Jan 24th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. /**
  2. * Node.js class that watches the CouchDB _changes API and emits events on new changes.
  3. */
  4. var EventEmitter = require('events').EventEmitter;
  5. var cradle = require('cradle');
  6.  
  7. CouchWatcher = function(options) {
  8. this.userid = options.userid;
  9. this.password = options.password;
  10. this.dbname = options.dbname;
  11. this.host = options.host || '127.0.0.1';
  12. this.port = options.port || 5984;
  13. this.heartbeat = options.heartbeat || 1000;
  14. };
  15.  
  16. CouchWatcher.prototype = new EventEmitter;
  17.  
  18. CouchWatcher.prototype.watch = function(filter, since) {
  19.  
  20. var self = this;
  21.  
  22. // Create new connection to CouchDB instance.
  23. var db = new (cradle.Connection)(self.host, self.port,
  24. {
  25. auth : {
  26. username : self.userid,
  27. password : self.password
  28. }
  29. }).database(self.dbname);
  30.  
  31. // Watch changes API and emit event with document.
  32. var options = { include_docs : true, feed : 'continuous', heartbeat : self.heartbeat};
  33. if(filter) {
  34. options.filter = filter;
  35. }
  36. if(since) {
  37. options.since = since;
  38. }
  39. db.changes(options).on('response', function(res) {
  40. res.on('data', function(change) {
  41. self.emit('doc', change.doc);
  42. });
  43. res.on('end', function() {
  44. self.emit('end');
  45. });
  46. });
  47.  
  48. };
  49.  
  50. exports.CouchWatcher = CouchWatcher;
Add Comment
Please, Sign In to add comment