1

“至少”是指将忽略所有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提供了我缺少的开箱即用的东西?

4

1 回答 1

2

您可以从metosin/schema-tools中使用一些东西:schema-tools.walk测试中甚至还需要一个代码:

(defn recursive-optional-keys [m]
  (sw/postwalk (fn [s]
                 (if (and (map? s) (not (record? s)))
                   (st/optional-keys s)
                   s))
               m))
于 2016-02-23T23:16:19.437 回答