Skip to content

Instantly share code, notes, and snippets.

@gjritter
Created July 7, 2010 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjritter/466926 to your computer and use it in GitHub Desktop.
Save gjritter/466926 to your computer and use it in GitHub Desktop.
var http = require('http'),
sys = require('sys'),
couchdb = require('./lib/couchdb'),
port = process.env.PORT || 8001,
COUCH_PORT = 5984,
COUCH_SERVER = 'localhost',
COUCH_USER = null,
COUCH_PASSWORD = null;
function getCounter(callback) {
var client = couchdb.createClient(COUCH_PORT, COUCH_SERVER, COUCH_USER, COUCH_PASSWORD),
db = client.db('node-heroku-counter'), counter = -1;
db.getDoc('counter', function(err, doc) {
if(err) {
sys.puts(sys.inspect(err));
} else {
counter = doc.counter;
}
callback(counter);
});
}
function incrementCounter() {
var client = couchdb.createClient(COUCH_PORT, COUCH_SERVER, COUCH_USER, COUCH_PASSWORD),
db = client.db('node-heroku-counter');
db.getDoc('counter', function(err, doc) {
if(err) {
sys.puts(sys.inspect(err));
} else {
doc.counter += 1;
db.saveDoc('counter', doc, function(err, ok) {
if(err) {
sys.puts(err.error + ', retrying...');
incrementCounter();
} else {
sys.puts('Counter incremented to ' + doc.counter);
}
});
}
});
}
http.createServer(function (req, res) {
switch(req.method) {
case 'GET':
getCounter(function(counter) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, ' + counter + '!\n');
});
break;
case 'POST':
incrementCounter();
res.writeHead(200, {'Content-Length': 0});
res.end();
break;
default:
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('Not Found\n');
}
}).listen(parseInt(port));
@gjritter
Copy link
Author

gjritter commented Jul 7, 2010

A node server that uses couchdb to provide a counter. The incrementCounter function attempts to update the counter in couchdb, and on a version conflict (or any other error for that matter) retries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment