Created
April 4, 2011 19:55
-
-
Save phreax/902285 to your computer and use it in GitHub Desktop.
couchdb act on changes with node
This file contains 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 app = require('app') | |
var assert = require('assert') | |
var db = app.db; | |
var get_state = function() { | |
db.get('_state', function(err,doc) { | |
if(err) { | |
console.log("processed_seq does not exist"); | |
return 0; | |
} | |
else { | |
var seq = doc.processed_seq; | |
console.log("processed sequence = "+seq); | |
if(seq != null && seq != undefined) | |
return seq; | |
else | |
return 0; | |
} | |
}); | |
} | |
var set_state = function(seq) { | |
db.get('state', function(err,doc) { | |
if(err) { | |
console.log("processed_seq does not exist"); | |
db.save('state',{processed_seq:0},function(e,res){console.log("saved state");}); | |
} | |
else { | |
var rev = doc._rev; | |
db.save('state',rev,{processed_seq:seq},function(e,res){console.log("saved state");}); | |
} | |
}); | |
} | |
// retrieve changes | |
var act_on_changes = function() { | |
var seq = get_state(); | |
console.log("get state = " + seq); | |
db.changes({since: seq }).on('response',function(res) { | |
res.on('data',function(change) { | |
console.log("changes:"); | |
console.log(change); | |
console.log("save_seq = " + seq); | |
seq++; | |
// persist procecced changes | |
set_state(seq); | |
}); | |
res.on('end', function() { | |
console.log("oops, connection closed"); | |
}); | |
}); | |
}; | |
// loop | |
act_on_changes(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment