Fork me on GitHub
#ring-swagger
<
2018-05-10
>
danielcompton03:05:23

Is there a way to use compojure-api and vanilla specs for validation, and not coercion?

ikitommi06:05:35

@danielcompton yes, you need to define a custom Coercion for that, with default-conforming set for all coercion scopes (body, string, response). Something like:

(require '[compojure.api.coercion.spec :as cs])
(require '[ring.util.http-response :as r])
(require '[compojure.api.sweet :as c])
(require '[clojure.spec.alpha :as s])

(def spec-validation
  (cs/create-coercion
    {:body {:default cs/default-conforming}
     :string {:default cs/default-conforming}
     :response {:default cs/default-conforming}}))

(s/def ::x int?)

(def app
  (c/POST "/echo" []
    :coercion spec-validation
    :body [body (s/keys :req-un [::x])]
    (r/ok body)))

(app {:request-method :post, :uri "/echo" :body-params {:x 1, :y 1}})
; {:status 200, :headers {}, :body {:x 1, :y 1}}

(app {:request-method :post, :uri "/echo" :body-params {:x "1"}})
; CompilerException clojure.lang.ExceptionInfo: Request validation failed ...

ikitommi06:05:11

default-conforming = no-op = just validation.

danielcompton06:05:40

Great, thanks!