在Clojure中的多态模式验证 [英] Polymorphic schema validation in Clojure
本文介绍了在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.
例如,这些值都有效:
{ :name "jane" :type :dog :barking true }
{ :name "alan" :type :bird :cheeping true }
{ :name "bert" :type :fish :swimming true }
但其他依赖于:type
的值。
例如,这将无效:
{ :name "phil" :type :bird :barking false }
如何表示这种模式?
我很乐意使用clj-schema或Prismatic模式。 / p>
I'm happy to use either clj-schema or Prismatic schema.
推荐答案
您可以使用prismatic.schema的 conditional
:
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})
这篇关于在Clojure中的多态模式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文