Skip to content

2.0.0 Content Negotiation (with Muuntaja)

Juho Teperi edited this page Dec 16, 2020 · 6 revisions

Content negotiation

Examples

With Muuntaja instance

(require '[compojure.api.sweet :refer :all])
(require '[ring.util.http-response :refer [ok]])
(require '[metosin.transit.dates :as transit-dates]) ;; https://github.com/metosin/metosin-common
(require '[muuntaja.core :as m])

;; create a muuntaja instance with custom transit-settings
(def muuntaja
  (m/create
    (update-in 
      muuntaja/default-options
      [:formats "application/transit+json"] 
      merge 
      {:decoder-opts {:handlers transit-dates/readers}
       :encoder-opts {:handlers transit-dates/writers}})))

(api
  {:formats muuntaja}
  (GET "/pizza" []
    (ok {:now (org.joda.time.DateTime/now)})))

With options

If options map is passed, it's automatically coerced into a Muuntaja instance

(api
  {:formats 
    (update-in 
      muuntaja/default-options
      [:formats "application/transit+json"] 
      merge 
      {:decoder-opts {:handlers transit-dates/readers}
       :encoder-opts {:handlers transit-dates/writers}})}
  (GET "/pizza" []
    (ok {:now (org.joda.time.DateTime/now)})))

Using Muuntaja outside of the api

(require '[muuntaja.middleware])

(def app
  (->
    (routes
      (api
        (POST "/echo" []
              :body [data {:name String}]
              (ok data)))
      (api
        (POST "/echo2" []
              :body [data {:name String}]
              (ok data))))
    (muuntaja.middleware/wrap-format)))

... or with configuration:

(def app
  (->
    (routes
      (api
        (POST "/echo" []
              :body [data {:name String}]
              (ok data)))
      (api
        (POST "/echo2" []
              :body [data {:name String}]
              (ok data))))
    (muuntaja.middeleware/wrap-format muuntaja)))