Fork me on GitHub
#clojure-spec
<
2020-02-04
>
kenny22:02:51

Will Spec2 provide a way to select the required keys of a nested Spec based on a dispatch value? For example, say you have a map that has a key ::items . The required keys for each map within the items list will vary based on the :type key on each item map. I could write add a top-level predicate to the ::items spec via s/and that would check the validity of each map in the items list against another defined spec. That would result in poor error messages though.

kenny23:02:53

Got it. You probably have a good idea of what it may look like already. In case it may be of any use, this is what I'm thinking we'll end up implementing internally for this problem.

(s/select
  ::report-input-data-schema
  [::instances
   {;; map of dispatch value to required keys
    ::instances {:default         []
                 :instance.type/a [:instance.a/prop1]
                 :instance.type/b [:instance.b/prop1]}
    ;; required keys for all maps
    :common     [:instance/status
                 :instance/name]
    ;; dispatch fn
    :dispatch   :type}])