add basic validation helper for checking against a schema definition

This commit is contained in:
Gered 2015-01-04 23:40:23 -05:00
parent 4fb8b7a002
commit d59bc300fa
2 changed files with 13 additions and 1 deletions

View file

@ -7,4 +7,5 @@
:dependencies [[org.clojure/clojure "1.6.0"] :dependencies [[org.clojure/clojure "1.6.0"]
[compojure "1.3.1" :scope "provided"] [compojure "1.3.1" :scope "provided"]
[ring/ring-core "1.3.1" :scope "provided"] [ring/ring-core "1.3.1" :scope "provided"]
[cheshire "5.3.1"]]) [cheshire "5.3.1"]
[prismatic/schema "0.3.3"]])

View file

@ -2,6 +2,7 @@
(:require (:require
[compojure.core :refer [routing]] [compojure.core :refer [routing]]
[ring.util.response :refer [response?]] [ring.util.response :refer [response?]]
[schema.core :as s]
[clj-webtoolbox.response :as response] [clj-webtoolbox.response :as response]
[clj-webtoolbox.routes.core :refer [destructure-route-bindings]])) [clj-webtoolbox.routes.core :refer [destructure-route-bindings]]))
@ -99,6 +100,16 @@
(if (f (get-in request k)) (if (f (get-in request k))
(safe request parent [param]))))) (safe request parent [param])))))
(defn validate-schema
"Validates the specified parameter by checking it against the given schema.
If it validates, the parameter is marked safe. Follows the same rules for
param/parent handling as validate."
([request param schema] (validate-schema request :params param schema))
([request parent param schema]
(let [k (if (sequential? param) (concat [parent] param) [parent param])]
(if (nil? (s/check schema (get-in request k)))
(safe request parent [param])))))
(defn transform (defn transform
"Transforms the specified parameter using function f which gets passed the value "Transforms the specified parameter using function f which gets passed the value
of the parameter. A nested parameter can be transformed by specifying it as a of the parameter. A nested parameter can be transformed by specifying it as a