Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic schema validation in Clojure

Tags:

schema

clojure

I want to use a schema to validate a request object. One of the values in the map determines which other fields are valid.

For example, these would all be valid:

{ :name "jane" :type :dog :barking true }
{ :name "alan" :type :bird :cheeping true }
{ :name "bert" :type :fish :swimming true }

Some fields are common. But others depend upon the value of :type.

For example, this would be invalid:

{ :name "phil" :type :bird :barking false }

How can such schema be expressed?

I'm happy to use either clj-schema or Prismatic schema.

like image 948
Drew Noakes Avatar asked May 28 '14 16:05

Drew Noakes


1 Answers

You can use prismatic.schema's conditional to accomplish this:

(s/conditional #(= (:type %) :bird) {:type (s/eq :bird) :chirping s/Bool}
               #(= (:type %) :fish) {:type (s/eq :fish) :swimming s/Bool}
               ...
               :default  {:type (s/eq :animal) :existing s/Bool})
like image 54
Arthur Ulfeldt Avatar answered Nov 12 '22 11:11

Arthur Ulfeldt