如何获得至少'架构?

时间:2016-02-23 19:02:46

标签: clojure plumatic-schema

至少'我的意思是会忽略所有disallowed-key错误的架构。 请考虑以下代码段:

(require '[schema.core :as s])

(def s {:a s/Int})

(s/check s {:a 1}) ;; => nil (check passed)
(s/check s {:a 1 :b 2}) ;; => {:b disallowed-key}

(def at-least-s (at-least s))

(s/check at-least-s {:a 1}) ;; => nil
(s/check at-least-s {:a 1 :b 2}) ;; => nil

关于at-least函数实现的第一个想法是将[s/Any s/Any]条目连接到初始模式:

(defn at-least [s]
  (conj s [s/Any s/Any]))

但不幸的是,这种实现不适用于嵌套地图:

(def another-s {:a {:b s/Int}})

(s/check (at-least another-s) {:a {:b 1} :c 2}) ;; => nil
(s/check (at-least another-s) {:a {:b 1 :d 3} :c 2}) ;; => {:a {:d disallowed-key}}

是否有可能获得适用于嵌套地图的at-least模式?或者也许prismatic/schema提供了我想要的开箱即用的东西?

1 个答案:

答案 0 :(得分:2)

您可以使用metosin/schema-toolsschema-tools.walk中的内容。甚至还有一个代码需要in the test

(defn recursive-optional-keys [m]
  (sw/postwalk (fn [s]
                 (if (and (map? s) (not (record? s)))
                   (st/optional-keys s)
                   s))
               m))