Fork me on GitHub
#reitit
<
2022-11-11
>
agigao14:11:28

Hello Clojurians, I've come across a rather confusing coercion behaviour - under :body-params coercion just throws validation error and under :form-params it does the coercion: Error:

(def app
  (ring/ring-handler
    (ring/router
      [
       ["/" {:name :root
             :get  (fn [_] {:status 200 :body "pong"})
             :post {:coercion   rcm/coercion
                    :parameters {:body [:map [:id uuid?]]}
                    :handler    (fn [{:keys [parameters]}]
                                  {:status 200
                                   :body   (-> parameters :form)})}}]]
      {:data {:middleware [rrc/coerce-exceptions-middleware
                           rrc/coerce-request-middleware
                           rrc/coerce-response-middleware]}})))
(app
  {:request-method :post
   :uri            "/"
   :body-params    {:id "644c1b76-4c3c-4067-8aeb-86236bcb5538"}})
{:status 400,
 :body {:schema "[:map {:closed true} [:id uuid?]]",
        :errors ({:path [:id],
                  :in [:id],
                  :schema "uuid?",
                  :value "644c1b76-4c3c-4067-8aeb-86236bcb5538",
                  :message "should be a uuid"}),
        :value {:id "644c1b76-4c3c-4067-8aeb-86236bcb5538"},
        :type :reitit.coercion/request-coercion,
        :coercion :malli,
        :in [:request :body-params],
        :humanized {:id ["should be a uuid"]}}}
Correct:
(def app
  (ring/ring-handler
    (ring/router
      [
       ["/" {:name :root
             :get  (fn [_] {:status 200 :body "pong"})
             :post {:coercion   rcm/coercion
                    :parameters {:form [:map [:id uuid?]]}
                    :handler    (fn [{:keys [parameters]}]
                                  {:status 200
                                   :body   (-> parameters :form)})}}]]
      {:data {:middleware [rrc/coerce-exceptions-middleware
                           rrc/coerce-request-middleware
                           rrc/coerce-response-middleware]}})))

(app
  {:request-method :post
   :uri            "/"
   :form-params    {:id "644c1b76-4c3c-4067-8aeb-86236bcb5538"}})
Result:
{:status 200, :body {:id #uuid"644c1b76-4c3c-4067-8aeb-86236bcb5538"}}

John Tran14:11:25

Wow. Thanks for sharing!