Created
July 7, 2010 16:37
-
-
Save gjritter/466926 to your computer and use it in GitHub Desktop.
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 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.