Fork me on GitHub
#reitit
<
2019-10-30
>
dharrigan13:10:40

You know a path-param, if it's an id, say 10, is there a built-in-way to say, extract this out as a number, rather than a string? Obviously, I could call (Integer/parseInt) on it, but I was wondering if there is something in the configuration that would just do that coercion for me automatically

dharrigan13:10:27

doing {{:keys [id]} :path-params} pulls out a "10"

ikitommi16:10:30

@dharrigan coersion does that for you automatically. Are you on frontend, backend or both?

ikitommi16:10:39

But, there should be docs for both, and example projects tooin the repo

dharrigan17:10:01

So, if I add in reitit.ring.coercion along with

dharrigan17:10:04

{:data {:coercion reitit.coercion.spec/coercion
              :middleware [rrc/coerce-exceptions-middleware
                           rrc/coerce-request-middleware
                           rrc/coerce-response-middleware]}})))

dharrigan17:10:07

all should be good?

dharrigan17:10:33

tried that, didn't work - have to look deeper

ikitommi17:10:54

@dharrigan the coerced parameters are under :parameters in request, did you look there?

dharrigan17:10:45

ah okay, investigating

dharrigan20:10:31

got it to work! thanks for the help @ikitommi

dharrigan20:10:57

(defn get-starship-by-id
  [{{{:keys [id]} :path} :parameters}]
  {:status 200 :body (-> (db/find-starship-by-id id)
                         (utils/map->string))})

(def router
  (ring/router
   ["/api"
    ["/starships" get-starships]
    ["/starships/:id" {:get get-starship-by-id
                       :coercion reitit.coercion.schema/coercion
                       :parameters {:path {:id s/Int}}}]]
   {:data {:middleware [rrc/coerce-exceptions-middleware
                        rrc/coerce-request-middleware
                        rrc/coerce-response-middleware]}}))

ikitommi20:10:25

Good to hear you got it working. The route data gets accumulates from root to leaves, it's a good practise to out :coercion to top-level, effecting all routes. Only reason not to do this is if you want to mix & match different coercion impls in a same routing tree.

dharrigan21:10:06

thanks! will refactor 🙂

dharrigan21:10:05

(def router
  (ring/router
   ["/api"
    ["/starships" get-starships]
    ["/starships/:id" {:get get-starship-by-id
                       :parameters {:path {:id s/Int}}}]]
   {:data {:coercion reitit.coercion.schema/coercion
           :middleware [rrc/coerce-exceptions-middleware
                        rrc/coerce-request-middleware
                        rrc/coerce-response-middleware]}}))

dharrigan21:10:09

works a treat

👍 4