This code was written to validate a very simple map of the structure of {:body {:grepString "grepp" :date "2014-05-03" :environment "nightly"}
This snippet is not idiomatic clojure.
(defn validate-request [req]
(let [json-vals (:body req)
grepStr (:grepString json-vals)
date (:date json-vals)
env (:environment json-vals)
errors (atom "")]
(if (empty? grepStr)
(swap! errors str "'grepString' must not be null or empty.\n"))
(if (empty? date)
(swap! errors str "'date' must not be null or empty.\n"))
(if (and (not (empty? date)) (invalid-date date))
(swap! errors str "'date' must be of the form 'YYYY-MM-DD' (i.e. '2016-04-03').\n"))
(if (empty? env)
(swap! errors str "'environment' must not be null or empty.\n"))
(if (not (valid-environment env))
(swap! errors str "'environment' must be one of the following 'nightly', 'nightly2', 'nightly3' or 'preprod'.\n"))
(if (not-empty @errors)
{:body @errors :status 400 :headers {"Content-Type" "text/plain"}}
{})
)
)
If I had more validation to do then looking at one of the validation tools mentioned on http://www.clojure-toolbox.com/ would be a very good way to go. In particular https://github.com/logaan/vlad was mentioned.
A nicer equivalent form is (with thanks to the clojure google groups):
(defn check-values [{{:keys [grepString date environment]} :body}]
(apply str (cond-> []
(empty? grepString) (conj "'grepString' must not be null or empty.\n")
(empty? date) (conj "'date' must not be null or empty.\n")
(and (not (empty? date)) (invalid-date date)) (conj "'date' must be of the form 'YYYY-MM-DD' (i.e. '2016-04-03').\n")
(empty? environment) (conj "'environment' must not be null or empty.\n")
(not (valid-environment environment)) (conj "'environment' must be one of the following 'nightly', 'nightly2', 'nightly3' or 'preprod'.\n")
)
)
)
(defn validate-request [req]
(let [errors (check-values req)]
(if (seq errors) ;; 'seq' is preferred by some over 'empty?'
{:body errors :status 400 :headers {"Content-Type" "text/plain"}}
{}
)
)
)