Polymorphic schema validation in Clojure

不问归期 提交于 2019-12-30 17:17:48

问题


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.


回答1:


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})


来源:https://stackoverflow.com/questions/23917495/polymorphic-schema-validation-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!