-
Notifications
You must be signed in to change notification settings - Fork 14
Walking around with scouchdb
Suppose I have a Scala class used to record item prices in various stores ..
case class ItemPrice(store: String, item: String, price: Number)
and I would like to store it in CouchDB through an API that converts it to JSON under the covers and issues a PUT/POST to the CouchDB server.
Here is a sample session that does this for a local CouchDB server running on localhost and port 5984 ..
// specification of the db server running val http = new Http val test = Db(Couch(), "test") // create the database http(test create) // create the Scala object val s = ItemPrice("Best Buy", "mac book pro", 3000) // create a document for the database with an id val doc = Doc(test, "best_buy") // add http(doc add s) // query by id to get the id and revision of the document val id_rev = http(test ref_by_id "best_buy") // query by id to get back the object // returns a tuple3 of (id, rev, object) val sh = http(test.by_id[ItemPrice]("best_buy")) // got back the original object sh._3.item should equal(s.item) sh._3.price should equal(s.price)
Suppose the price of a mac book pro has changed in Best Buy and I get a new ItemPrice. I need to update the document that I have in CouchDB with the new ItemPrice object. For updates, I need to pass in the original revision that I would like to update ..
val new_itemPrice = //.. http(doc update(new_itemPrice, sh._2))
The Scala client is at a very early stage. All the above stuff works now, a lot more have been planned and is present in the roadmap. The main focus has been on the non intrusiveness of the framework, so that the Scala objects remain pure to be used freely in other contexts of the application. The library uses the goodness of Nathan Hamblen’s dispatch (http://databinder.net/dispatch) library, which provides elegant Scala wrappers over apache commons Java http client and a great JSON parser with a set of extractors.