How to get 'at-least' schema?

219 views Asked by At

By 'at-least' I mean schema that will ignore all disallowed-key errors. Consider the following snippet:

(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

The first idea about implementation of at-least function was to conjoin [s/Any s/Any] entry to initial schema:

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

but unfortunately such implementation won't work for nested maps:

(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}}

Is there's a possibility to get at-least schemas that work for nested maps as well? Or maybe prismatic/schema provides something out of the box that I'm missing?

1

There are 1 answers

1
Piotrek Bzdyl On BEST ANSWER

There is something you can use from metosin/schema-tools: schema-tools.walk. There is even a code that you need 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))