Skip to content

Instantly share code, notes, and snippets.

@bmabey
Last active October 13, 2017 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmabey/ea68b00e48f914ad3a0d4aa31c01e196 to your computer and use it in GitHub Desktop.
Save bmabey/ea68b00e48f914ad3a0d4aa31c01e196 to your computer and use it in GitHub Desktop.
(require '[spec-tools.core :as st])
(require '[spec-tools.spec :as st.s])
(require '[clojure.spec.alpha :as s])
(s/def ::cheese st.s/string?)
(s/def ::stuff st.s/int?)
(s/def ::bar (st/spec (s/keys :req-un [::cheese])))
(s/def ::foo (st/spec (s/keys :req-un [::stuff])))
(s/def ::response (s/or :b ::bar :f ::foo))
(def cheddar {:cheese "cheddar"})
(def stuff {:stuff 42})
(s/valid? ::response cheddar) ;; => true
(s/valid? ::response stuff) ;; => true
(def testapp
(api
{:coercion :spec}
(POST "/cheese" []
:return ::response
:body [body st.s/map?]
(resp/ok cheddar))
(POST "/stuff" []
:return ::response
:body [body st.s/map?]
(resp/ok stuff))))
(-> {:request-method :post
:uri "/stuff"
:headers {"content-type" "application/json"}
:body "{\"something\": \"good\"}"}
testapp
:body
slurp) ;; # => {"stuff": 42} (it works)
(-> {:request-method :post
:uri "/cheese"
:headers {"content-type" "application/json"}
:body "{\"something\": \"good\"}"}
testapp
:body
slurp) ;; this blows up
;; {"spec":"(spec-tools.core/spec {:spec (clojure.spec.alpha/or :b :user/body :f :taskstore.web/foo), :type nil})","problems":[{"path":["f"],"pred":["clojure.core/fn",["%"],["clojure.core/contains?","%","stuff"]],"val":{"cheese":"cheddar"},"via":["user/response","taskstore.web/foo"],"in":[]}],"type":"compojure.api.exception/response-validation","coercion":"spec","value":{"cheese":"cheddar"},"in":["response","body"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment