Wednesday 10 August 2011

A simple Clojure web app

I thought I'd start with a simple example showing why I'm coming to love Clojure. This is a small web app that accepts a GET request with an id, hits a CouchDB database, executes some simple business logic then returns the results as json.
What's interesting is that it does all this without using business objects, mappers, etc.

Clojure allows you to deserialize the json response from Couch into a hash-map and access the elements of that hash-map via symbols like so (client :address), no need for strings or accessing by a numerical index. As you can see this allows you to access values in the hash-map like fields on an object.

Clojure also has a thrush (or pipe) operator -> which can be used to pass objects into methods. While this is only syntactic sugar it allows you to use functions as if they where methods. e.g:
(-> client print-name-and-address)

This approach may not meet everyone's needs but I think it's a really great way to make lightweight, easily extensible, data driven web applications.
In the following example all the code is lumped together in 1 file just for the sake simplicity. In production code you would probably want to brake functions out into separate files for those that work on json, documents & vehicles as well as the core routing logic. (Error handling has been omitted to keep the example simple)