Clojure中的多态模式验证

Dre*_*kes 12 schema clojure

我想使用模式来验证请求对象.地图中的一个值确定哪些其他字段有效.

例如,这些都是有效的:

{ :name "jane" :type :dog :barking true }
{ :name "alan" :type :bird :cheeping true }
{ :name "bert" :type :fish :swimming true }
Run Code Online (Sandbox Code Playgroud)

有些领域很常见.但其他人依赖于价值:type.

例如,这将是无效的:

{ :name "phil" :type :bird :barking false }
Run Code Online (Sandbox Code Playgroud)

如何表达这种模式?

我很高兴使用clj-schema或Prismatic架构.

Art*_*ldt 14

您可以使用prismatic.schema conditional来完成此任务:

(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})
Run Code Online (Sandbox Code Playgroud)