metosin / malli

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

`m/explain` should prune the schemas under `:multi` that do not match the dispatch value #923

Open PavlosMelissinos opened 11 months ago

PavlosMelissinos commented 11 months ago

If you m/explain invalid data using a multi-schema, the explainer shows the entire multi-schema, not just the matching part. This can make spotting errors harder. I think it would be better to just use the part that is relevant when there's a clear dispatch value.

Example

(m/explain
  [:multi {:dispatch :type}
   [:sized [:map [:type keyword?] [:size int?]]]
   [:human [:map [:type keyword?] [:name string?] [:address [:map [:country keyword?]]]]]]
  {:type :sized, :sizey 10})

Desired result

{:schema [:map [:type keyword?] [:size int?]],
 :value {:type :sized, :sizey 10},
 :errors
 ({:path [:size],
   :in [:size],
   :schema [:map [:type keyword?] [:size int?]],
   :value nil,
   :type :malli.core/missing-key})}

Actual result

{:schema
 [:multi
  {:dispatch :type}
  [:sized [:map [:type keyword?] [:size int?]]]
  [:human
   [:map
    [:type keyword?]
    [:name string?]
    [:address [:map [:country keyword?]]]]]],
 :value {:type :sized, :sizey 10},
 :errors
 ({:path [:sized :size],
   :in [:size],
   :schema [:map [:type keyword?] [:size int?]],
   :value nil,
   :type :malli.core/missing-key})}

Corner case - Unknown dispatch value

When the data doesn't match any of the valid dispatch values of the multi-schema, malli should either revert to the current behaviour or ideally show a message that lets the user know that no schema is matched (the user still doesn't need to see the entire multi-schema)