Fork me on GitHub
#reitit
<
2020-12-10
>
kommen13:12:34

is there any precedence in how one would implement a dev workflow (https://github.com/metosin/reitit/blob/5efdc67954ebae194fa45c8b0deaa05bf157ca73/doc/advanced/dev_workflow.md#an-easy-fix) with reitit.pedestal?

Ronny Li21:12:33

Hi I'm trying to run an example in the reitit README (https://github.com/metosin/reitit/blob/master/doc/ring/coercion.md) but I'm getting an error. The idea is a POST endpoint that adds together parameters from query, body, and path.

(def plus-endpoint
  {:parameters {:query {:x s/Int}
                :body {:y s/Int}
                :path {:z s/Int}}
   :responses {200 {:body {:total s/Num}}}
   :handler (fn [{:keys [parameters]}]
              (let [total (+ (-> parameters :query :x)
                             (-> parameters :body :y)
                             (-> parameters :path :z))]
                {:status 200
                 :body {:total total}}))})

(def handler
  (ring/ring-handler
    (ring/router
      [["/plus/:z" {:post plus-endpoint}]]
      {:data {:coercion rsk/coercion                        ; plumatic schema
              :middleware [exception/exception-middleware
                           rrc/coerce-exceptions-middleware
                           rrc/coerce-request-middleware
                           rrc/coerce-response-middleware]}})))
When I test with curl, however I get a schema error saying that body-params is nil
curl --header "Content-Type: application/json" \
--request POST \
--data '{"y": 2}' \
'localhost:6543/plus/3?x=1'

[:schema {:x "Int", "Keyword" "Any"}][:errors "(not (map? [nil]))"][:type :reitit.coercion/request-coercion][:coercion :schema][:value nil][:in [:request :query-params]]
Any thoughts on where I'm going wrong?

3
Ronny Li21:12:43

I'm guessing this example is actually incomplete and I need to first include middleware that adds the :body-params keyword, is that right?

Dave Russell21:12:29

Yep 🙂 You need middleware to add both :query-params and :body-params. See https://github.com/metosin/reitit/blob/master/examples/ring-spec-swagger/src/example/server.clj#L89 example. muuntaja for :body-params and the built-in parameters-middleware for the :query-params and :form-params

Dave Russell21:12:16

It should perhaps be noted that, in the example you linked, app is called directly with a mocked ring request. But since you're coming in through cURL, you need the middleware (as you pointed out).

Ronny Li22:12:10

thank you Dave! That example is perfect. I just copied almost all of the middleware verbatim minus swagger and multipart 🙂