Skip to content

Instantly share code, notes, and snippets.

@jarohen
Created September 20, 2012 19:59
Show Gist options
  • Select an option

  • Save jarohen/3758002 to your computer and use it in GitHub Desktop.

Select an option

Save jarohen/3758002 to your computer and use it in GitHub Desktop.
Liberator - issue #6
(ns liberator.gist
(:use [liberator.core :only [defresource request-method-in]]
[compojure.core :only [defroutes ANY]]
[ring.adapter.jetty :only [run-jetty]]))
(defn create-new-ticket []
;; create the ticket, and return the url
"/tickets/new")
(defn get-all-tickets []
;; load all of the tickets
"all tickets")
;; define the tickets resource, which handles the GET and the POST requests
(defresource tickets-resource
:method-allowed? (request-method-in :get :post)
;; I'm only using text/plain here for the example - this should probably be JSON/XML/etc
:available-media-types ["text/plain"]
:post! (fn [context]
(let [url (create-new-ticket)]
;; returning a map from post! adds the :new-ticket-url to the context
{:new-ticket-url url}))
:post-redirect? true
:see-other (fn [context]
;; we just retrieve the :new-ticket-url that we put in the context, and return it
;; Liberator handles the rest!
(:new-ticket-url context))
;; handle-ok handles the GET requests
:handle-ok (fn [context] (get-all-tickets)))
;; attach the resource to a route (this is Compojure, you can also use Moustache)
(defroutes routes
(ANY "/tickets" [] tickets-resource))
;; run the jetty server
(run-jetty #'routes {:port 3000})
@sougatabh
Copy link
Copy Markdown

Cool really helpful.

Copy link
Copy Markdown

ghost commented Aug 15, 2013

How to handle potential failures in post! E.g. how to report that DB transaction has failed?

@neotyk
Copy link
Copy Markdown

neotyk commented Nov 7, 2013

@lambder You can return status in map that is returned from :post! and later analyse contents of context in :see-other :post-redirect?
HTH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment