Resources - acidlabs/rip GitHub Wiki
Similarly to Rails routes configuration, RIP provides a resources
function to define RESTful-like routes, including coll
and memb
functions for collection and member routes respectively. Resources can also be nested!.
Example:
(resources :users
(coll :index :get (routefn [] "This is an index for users"))
(memb :show :get (routefn [id] (str "This is a show for user with id " id)))
(resources :books
(memb :show :get (routefn [id books-id]
(str "This is a show for book with id " book-id
" of user with id " id)))))
To keep the destructuring syntax from compojure's routes, RIP provides the routefn
macro.
Functions coll
and memb
receive the name of the action, the method, a request handler and an optional map with a sufix for path and a url-handler to help creating HATEOAS links.
To obtain the request handler to be passed to ring, use the ->handler
function. This will compile into a compojure's route function.
Example:
(->handler (resources :users
(coll :add :post (routefn [] "This is a post for users")))
;;=> (routes (POST "/users" [] "This is a post for users"))
To create a resources definition assigned to a value use the defresources
macro. The macro will return the compiled route handler.
Example:
(routes
(defresources users
(coll :index :get (routefn [] "This is an index for users"))))
The ->url
function returns the result from the url-handler passed to coll
and memb
. ->url receives a vector with the resources definition value and the actions, similar to get-in
function, and an optional map with route-params and/or query-params.
Example:
(defresources users
(coll :index :get (routefn [] "This is an index for users"))
(memb :show :get (routefn [id] (str "This is a show for user with id " id))
(resources :books
(memb :show :get (routefn [id books-id]
(str "This is a show for book with id " book-id
" of user with id " id))))
(->url [users :index] {:query-params {:id 1}})
;;=> "/users?id=1"
(->url [users :show] {:route-params {:id 1}})
;;=> "/users/1"
(->url [users :books :show] {:route-params {:id 1 :books-id 2}})
;;=> "/users/1/books/2"
Some predefined actions for resources are available in rip.action
namespace.