all muuntaja formats wrapped

This commit is contained in:
Tommi Reiman 2018-07-22 14:59:19 +03:00
parent 5c0cf19ef1
commit 3a8eae6324
2 changed files with 84 additions and 3 deletions

View file

@ -4,13 +4,36 @@
[clojure.spec.alpha :as s]))
(s/def ::muuntaja (partial instance? m/Muuntaja))
(s/def ::spec (s/keys :opt-un [::muuntaja]))
(def format-middleware
{:name ::formats
:spec (s/keys :opt-un [::muuntaja])
:spec ::spec
:compile (fn [{:keys [muuntaja]} _]
(if muuntaja
{:data {:swagger {:produces (m/encodes muuntaja)
:consumes (m/decodes muuntaja)}}
:wrap (fn [handler]
(muuntaja.middleware/wrap-format handler muuntaja))}))})
:wrap #(muuntaja.middleware/wrap-format % muuntaja)}))})
(def format-negotiate-middleware
{:name ::formats
:spec ::spec
:compile (fn [{:keys [muuntaja]} _]
(if muuntaja
{:wrap #(muuntaja.middleware/wrap-format-negotiate % muuntaja)}))})
(def format-request-middleware
{:name ::formats
:spec ::spec
:compile (fn [{:keys [muuntaja]} _]
(if muuntaja
{:data {:swagger {:consumes (m/decodes muuntaja)}}
:wrap #(muuntaja.middleware/wrap-format-request % muuntaja)}))})
(def format-response-middleware
{:name ::formats
:spec ::spec
:compile (fn [{:keys [muuntaja]} _]
(if muuntaja
{:data {:swagger {:produces (m/encodes muuntaja)}}
:wrap #(muuntaja.middleware/wrap-format-response % muuntaja)}))})

View file

@ -83,3 +83,61 @@
(is (= #{"application/edn"}
(produces path)
(consumes path)))))))
(deftest muuntaja-swagger-parts-test
(let [app (ring/ring-handler
(ring/router
[["/request"
{:middleware [muuntaja/format-negotiate-middleware
muuntaja/format-request-middleware]
:get identity}]
["/response"
{:middleware [muuntaja/format-negotiate-middleware
muuntaja/format-response-middleware]
:get identity}]
["/both"
{:middleware [muuntaja/format-negotiate-middleware
muuntaja/format-response-middleware
muuntaja/format-request-middleware]
:get identity}]
["/swagger.json"
{:get {:no-doc true
:handler (swagger/create-swagger-handler)}}]]
{:data {:muuntaja m/instance}}))
spec (fn [path]
(-> {:request-method :get :uri "/swagger.json"}
(app) :body :paths (get path) :get))
produces (comp :produces spec)
consumes (comp :consumes spec)]
(testing "just request formatting"
(let [path "/request"]
(is (nil? (produces path)))
(is (= #{"application/json"
"application/transit+msgpack"
"application/transit+json"
"application/edn"}
(consumes path)))))
(testing "just response formatting"
(let [path "/response"]
(is (= #{"application/json"
"application/transit+msgpack"
"application/transit+json"
"application/edn"}
(produces path)))
(is (nil? (consumes path)))))
(testing "just response formatting"
(let [path "/both"]
(is (= #{"application/json"
"application/transit+msgpack"
"application/transit+json"
"application/edn"}
(produces path)))
(is (= #{"application/json"
"application/transit+msgpack"
"application/transit+json"
"application/edn"}
(consumes path)))))))