default coercion format reads from Muuntaja keys

This commit is contained in:
Tommi Reiman 2018-06-11 08:52:53 +03:00
parent 73a5bd2d3d
commit bcc2564498
2 changed files with 49 additions and 4 deletions

View file

@ -66,9 +66,12 @@
:request request
:response response}))))
(defn extract-request-format-default [request]
(-> request :muuntaja/request :format))
;; TODO: support faster key walking, walk/keywordize-keys is quite slow...
(defn request-coercer [coercion type model {:keys [extract-request-format]
:or {extract-request-format (constantly nil)}}]
:or {extract-request-format extract-request-format-default}}]
(if coercion
(let [{:keys [keywordize? open? in style]} (ring-parameter-coercion type)
transform (comp (if keywordize? walk/keywordize-keys identity) in)
@ -82,8 +85,11 @@
(request-coercion-failed! result coercion value in request)
result))))))
(defn extract-response-format-default [request response]
(-> request :muuntaja/response :format))
(defn response-coercer [coercion body {:keys [extract-response-format]
:or {extract-response-format (constantly nil)}}]
:or {extract-response-format extract-response-format-default}}]
(if coercion
(let [coercer (-response-coercer coercion body)]
(fn [request response]

View file

@ -4,9 +4,13 @@
[reitit.ring :as ring]
[reitit.ring.coercion :as rrc]
[reitit.coercion.spec :as spec]
[reitit.coercion.schema :as schema])
[reitit.coercion.schema :as schema]
#?(:clj
[muuntaja.middleware])
[jsonista.core :as j])
#?(:clj
(:import (clojure.lang ExceptionInfo))))
(:import (clojure.lang ExceptionInfo)
(java.io ByteArrayInputStream))))
(defn handler [{{{:keys [a]} :query
{:keys [b]} :body
@ -145,3 +149,38 @@
(testing "invalid response"
(let [{:keys [status]} (app invalid-request2)]
(is (= 500 status))))))))))
#?(:clj
(deftest muuntaja-test
(let [app (ring/ring-handler
(ring/router
["/api"
["/plus"
{:post {:parameters {:body {:int int?, :keyword keyword?}}
:responses {200 {:body {:int int?, :keyword keyword?}}}
:handler (fn [{{:keys [body]} :parameters}]
{:status 200
:body body})}}]]
{:data {:middleware [muuntaja.middleware/wrap-format
rrc/coerce-request-middleware
rrc/coerce-response-middleware]
:coercion spec/coercion}}))
request (fn [content-type body]
(-> {:request-method :post
:headers {"content-type" content-type, "accept" content-type}
:uri "/api/plus"
:body body}))
data-edn {:int 1 :keyword :kikka}
data-json {:int 1 :keyword "kikka"}]
(testing "json coercion"
(let [e2e #(-> (request "application/json" (ByteArrayInputStream. (j/write-value-as-bytes %)))
(app) :body (slurp) (j/read-value (j/object-mapper {:decode-key-fn true})))]
(is (= data-json (e2e data-edn)))
(is (= data-json (e2e data-json)))))
(testing "edn coercion"
(let [e2e #(-> (request "application/edn" (pr-str %))
(app) :body slurp (read-string))]
(is (= data-edn (e2e data-edn)))
(is (thrown? ExceptionInfo (e2e data-json))))))))