Search code examples
clojureroutesparseintcompojurering

Typecast compojure route's id to integer automatically


I have something like this (GET "/photo/:id/tags/:tag-id/...")

and thus for every route inside that context I have to typecast these ids to Integer explicitly. Is there any way to achieve this automatically or have a common place to typecast ids instead of each controller's action?


Solution

  • As of Compojure 1.4.0, you can also supply coercion functions for parameters using the :<< keyword:

    [x :<< as-int]
    

    In the above case, the parameter x will be passed through the as-int function before being assigned. If any coercion function returns nil, then the coercion is considered to have failed, and the route will not match.

    Example:

    (defroutes app 
      (GET "/customers" [] customers)
      (GET "/suppliers" [] suppliers)
      (GET "/accounts" [] accounts)
      (context "/statements" []
               (GET "/" [] statements)
               (GET "/:id" [id :<< as-int] (single-statement id))))