Search code examples
clojurering

how to access / pass the request map in a moustache handler


I want to create a handler function which takes two inputs. One is a parameter taken from the url /name, and second is a param from the query string /name?x=3

(def my-app (app
               [page-name] (handler page-name)))

(defn handler
  [{:keys [params]} page-name]
  (let [x (params "x")]
    (-> (page-templ page-name x) response constantly)))

The above fails because the handler is expecting 2 params, however I am only passing one.

How do I get hold of the request map, and pass it to the handler ?

The request map in the above case contains a param named x.


Solution

  • It is best if you could dispatch on the page name, like that:

    (app
     [""] (index-page)
     ["login"] (serve-login))
    

    Here functions index-page and serve-login return function of one argument.

    (defn index-page[]
      (fn [req] ..))
    

    req is the request that will contain all the url parameters in key/value map. To get parameter value do this:

    (-> req (get :params) (get :x))
    

    So the full solution would look something like this:

    (def my-app (app
                   ["page1-name"] (handler)))
    
    (defn handler []
      (fn [req]
        (let [x (-> req :params :x)]
          (-> (page-templ page-name x) response))))
    

    EDIT: Don't forget to wrap you application into (wrap-keyword-params) and (wrap-params), here's how you can do it:

    (def my-wrapped-app
      (-> my-app
       (wrap-keyword-params)
       (wrap-params))