validation - Using clj-schema to validate that a sequence of maps has unique values for a given key -
I have a request object that has a sequence of maps. I'd like to validate that there are no duplicate values for the key given in those maps. For example, it is valid:
[{id: 1,: data "foo"} {: id 2,: data "bar"}]
This is invalid because it has a duplicate of : id 1
:
[{id: 1,: data "foo"} {: id2, : Data "bar"} {: id 1,: data "baz"}]
I currently have something similar:
(def- Map-schema item-schema [[: id] integer? [: Data] string?]) How to express the expression of this specificity using Def-map-schema clj-schema
P>
The CLJ-schema provides a function, clj-schema.schema / simple-schema
, which can be used to predict arbitrarily in schemas < Code> with-unique-key-map- schema:
How to use it to implement defn maps-with-unique-key? [K] (s) Do / simple-schema [(S / map sequence?) (FN [xs] (= (xs count) (count (different (map # (get% k) xs)))))))))
In REPL:
(v / valid? (With-unique map with map: ID) []); = {(Id: 0: foo "bar"} {: id 1: foo "baz"} {: id 2: foo "quux"} = true (v / valid? (With mac-unique-key? ]] == (v / is valid? ([With unique-key-map: id] [{id: 0: foo "bar"} {: id 1: foo "baz"} {: id 0: foo " Queue "}] = = ((ID-of-unique-key ?: id) [[" Do not map "] {: id 0: foo" bar "} {: id 1: foo" baz "} {: ID 2: Foo" quux "}] = = << / code>
(My original answer for Prismatic schema is as follows.)
I do not think that the standard schema distribution has a schematic schema for this, but it is always possible Here is a sketch:
(defrecord MapsWithUniqueKey [k] s / schema (Walker [This] is a sketch of (Fn [x] (if (and (or (seq? X) (vector? X) (every? Map? X) (each? # (In it?% K) x) (== (count x) (count (Separate (map # (get% k)))) ()) () [(According to 'map' in this list) (X 'Schema. Macros / Verification-Error with X' (list) - maps-with-unique-key? With the example:
(s / check (-> mappsweuthUKKI: ID) [id: ID-ID-unique (with schema.utils / value-name x))) {} Id: foo "quux"}] = = zero ();) S / check (-> MappsWeEUKKI: ID) [{ID: Foo "bar"} {: id 2: foo "baz"} {: id 1: foo "quux"}] == (not (-im- Unique-key-with-map: id a-clojure.lang.PersistentVector))
returns zero
returned from the first call, while the latter Return value is a schema.utils.ValidationError
.
Comments
Post a Comment