Skip to content

Instantly share code, notes, and snippets.

@bkirkbri
Created June 24, 2012 19:57
Show Gist options
  • Save bkirkbri/2984680 to your computer and use it in GitHub Desktop.
Save bkirkbri/2984680 to your computer and use it in GitHub Desktop.
Named route example
;; Higher-order fns that wrap handlers need to preserve the route metadata
;; No problem: just generate a version that does
(def for-host+ (preserve-routes for-host))
(def make-REST-handlers+ (preserve-routes make-REST-handlers))
;; Naming is optional can be arbitrarily deep in the tree as long as all
;; composition along the branch preserves route metadata.
;; This syntax is a rough first cut, another option is (GET :name "/" [] handler)
(def app
(routes (for-host+ "opp-admin.com"
(context "/accounts/:acct-id" [acct-id]
(route :account (GET "/" [] account-handler))
(route :payments (GET "/payments" [] payments-handler))
(route :payment (GET "/payments/:pmt-id" [pmt-id] payment-handler)))
(context "/referrals" []
(route :referrals (GET "/" [] referrals-handler))
(route :referral (GET "/:ref-id" [ref-id] referral-handler))))
(for-host+ "opp-cp.com"
(GET "/unnamed" [] some-handler)
(route :artwork (ANY "/artwork/:id" [id]
(make-REST-handlers+ {:id id ...}))))))
;; Walk the tree and extract the named routes
(def url-map (routes->urls app))
(println "Check out" (url-for url-map :artwork [123]))
;; Or generate a mapper fn that closes over the map of named routes
(def url-mapper (routes->url-mapper app))
(println "AKA" (url-mapper :artwork [123]))
;; Using middleware is as simple as:
(def wrap-params+ (preserve-routes wrap-params))
(def wrapped (wrap-params+ app))
;; or, for convenience:
(def wrapped (middleware wrap-params app))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment