reitit

Felipe 2024-04-13T13:34:27.981989Z

maybe similar to the previous question: does the coercion example from the README support content negotiation? muuntaja being there makes me thing so, but I can only get it to give me JSON

✅ 1
Felipe 2024-04-13T13:34:56.590229Z

(ns flib.reitit
  (:require [muuntaja.core :as mu]
            [reitit.coercion.malli]
            [reitit.ring :as ring]
            [reitit.ring.coercion :as rrc]
            [reitit.ring.middleware.dev :as middleware.dev]
            [reitit.ring.middleware.muuntaja :as muuntaja]
            [reitit.ring.middleware.parameters :as parameters]))

(def router
  (ring/router
   ["/api"
    ["/math"
     {:get {:parameters
            {:query
             [:map
              [:x int?]
              [:y int?]]}

            :responses
            {200 {:body [:map [:total int?]]}}

            :handler
            (fn [{{{:keys [x y]} :query} :parameters}]
              {:status 200
               :body   {:total (+ x y)}})}}]]

   ;; router data affecting all routes
   {:reitit.middleware/transform middleware.dev/print-request-diffs
    :data {:coercion   reitit.coercion.malli/coercion
           :muuntaja   mu/instance
           :middleware [parameters/parameters-middleware
                        rrc/coerce-request-middleware
                        muuntaja/format-response-middleware
                        rrc/coerce-response-middleware]}}))

(comment

  (def ring-handler
    (let [dev-mode true
          f (fn [] (reitit.ring/ring-handler router))]
      (if dev-mode
        (reitit.ring/reloading-ring-handler f)
        (f))))

  (-> (ring-handler {:request-method :get
                     :uri "/api/math"
                     :query-params {:x "1", :y "2"}
                     :headers {"Accept" "application/edn"}})
      :body
      slurp)
  ;; => "{\"total\":3}"

  nil)

Felipe 2024-04-13T13:36:03.013349Z

Felipe 2024-04-13T13:40:26.620709Z

found format-negotiate, but still

Felipe 2024-04-13T13:41:41.562129Z

ah WOW, I missed that (I think?) Ring will lowercase all header keys.

Felipe 2024-04-13T13:41:58.828859Z

so "accept" "application/edn" does work

Felipe 2024-04-13T13:43:02.186749Z

but you do need format-negotiate-middleware