Clojure 中的多态模式验证 [英] Polymorphic schema validation in Clojure

查看:15
本文介绍了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 }

有些字段是通用的.但其他的取决于 :type 的值.

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

例如,这将是无效的:

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

如何表达这样的模式?

我很乐意使用 clj-schema 或 Prismatic 模式.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆