metosin / malli

High-performance data-driven data specification library for Clojure/Script.
Eclipse Public License 2.0
1.5k stars 211 forks source link

Adds `:pred` option to `m/-map-schema` #767

Closed fr33m0nk closed 2 years ago

fr33m0nk commented 2 years ago

Context:

(def EntityMap (m/-map-schema {:pred entity?}))

(m/validate EntityMap ...)

* `:pred` key-value is optional, just like `:lazy` and `:naked-keys`. In absence of explicit value, `map?` is used as default predicate (referred to as `pred?` in code)

Usage with PR:
```clojure
;; regular usage still works just fine
(m/validate
  (m/schema [:map
             [:member/id uuid?]
             [:member/organization [:map
                                    [:organization/id uuid?]]]])
  {:db/id 409018325533822,
   :member/id #uuid"ff995e8b-77c0-4c03-a8a8-c5db609a2f16",
   :member/organization {:db/id 17592186045562, :organization/id #uuid"25dd7d64-6f83-49fe-bd36-253e985b3e00"}})
=> true

;; a custom predicate fn
(defn entity?
  [entity]
  (instance? datomic.query.EntityMap entity))

;; example member entity
member-entity
=>
{:db/id 409018325533822,
 :member/id #uuid"ff995e8b-77c0-4c03-a8a8-c5db609a2f16",
 :member/organization {:db/id 17592186045562, :organization/id #uuid"25dd7d64-6f83-49fe-bd36-253e985b3e00"}}

;; validation of entity

(m/validate
  (m/schema [:entity-map
             [:member/id uuid?]
             [:member/organization [:entity-map
                                    [:organization/id uuid?]]]]
            {:registry (assoc (m/default-schemas) :entity-map (m/-map-schema {:pred entity?}))})
  mmm)
=> true