At least one additional key present in the clojure schema

Let's say I have the following diagram for some input that I get from the outside world:

(def my-schema {(s/optional-key :foo) Bool (s/optional-key :baz) Bool (s/optional-key :bar) Bool}) 

With the above, all or none of the keys can be present or absent on the card I am checking makes sense. However, if I want to make sure that at least one of them is present?

I can, of course, do an additional separate check after Schema has checked the above and made sure that the key count is> = 1, but I'm curious if there is a way to provide this in the schema definitions themselves.

Thoughts?

+5
source share
1 answer

You can specify any predicate that you want in your schemas:

 (def my-schema (s/both (s/pred (complement empty) 'not-empty) {(s/optional-key :foo) Bool (s/optional-key :baz) Bool (s/optional-key :bar) Bool})) 

If you ask how to check a map using only the built-in predicates, you can write:

 (def my-schema (s/both {(s/optional-key :foo) Bool (s/optional-key :baz) Bool (s/optional-key :bar) Bool} (s/either {:foo Bool s/Any s/Any} {:baz Bool s/Any s/Any} {:bar Bool s/Any s/Any}))) 

which is pretty ugly and much more verbose than the pred example

+3
source

Source: https://habr.com/ru/post/1200493/


All Articles