Compojure Demystified with an example – Part 6
In this part we will start implementing edit and delete functionalities.
We are going to build these services,
Edit address – PUT – http://localhost:8080/addresses/:id
Delete address – DELETE – http://localhost:8080/addresses/:id
1) Adding PUT and DELETE route
Edit routes.clj
(ns address_book.routes
(:use [compojure.core])
(:require [address-book.address :as address]
[address-book.middleware :as mdw]
[compojure.route :as route]
[clj-json.core :as json]))
(defn json-response [data & [status]]
{:status (or status 200)
:headers {"Content-Type" "application/json"}
:body (json/generate-string data)})
(defroutes handler
(GET "/addresses" [] (json-response (address/find-all)))
(GET "/addresses/:id" [id] (json-response (address/find id)))
(POST "/addresses" {params :params} (json-response (address/create params)))
(PUT "/addresses/:id" {params :params} (json-response (address/update (params "id") params)))
(DELETE "/addresses/:id" [id] (json-response (address/delete id )))
(route/files "/" {:root "public"})
(route/not-found "Page not found"))
(def address-book
(-> handler
mdw/wrap-request-logging))
As you can see it is pretty straight forward to add PUT and DELETE route.
What is up with params?
In previous version of Compojure there were some magic variables, like params, session etc. From version 0.4 there are no more magic variables. Instead Compojure provides a map “params”. “params” map will contain all request information. For some reason, params map have a key :params which contains request parameters. That is why we have do {params :params}. I wish they will rename “params” to something else.
Instead of doing {params :params}, the compojure document states that we could do [params id] and when compojure detects a vector, instead of a map it will assign the parameters to each value of the vector. But for some reason, I was not able to make it work.
Front End code
Checkout from github for front end code. Warning: front end code is bad, do not take this as an example.
In next part we will see how to send flash messages.
Source code is now available at github. Created branches for each part.
Next part is posted.
