Skip to content

Commit

Permalink
Merge pull request #397 from metosin/optionalles-default
Browse files Browse the repository at this point in the history
Ignore optional properties in `default-value-transformer`
  • Loading branch information
ikitommi authored Mar 18, 2021
2 parents 2e57a80 + 2b68326 commit 5193152
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/malli/transform.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -380,18 +380,23 @@
([]
(default-value-transformer nil))
([{:keys [key defaults] :or {key :default}}]
(let [get-default (fn [schema] (let [default (some-> schema m/properties key)]
(if (some? default) default (some->> schema m/type (get defaults) (#(% schema))))))
(let [get-default (fn [schema]
(if-some [default (some-> schema m/properties key)]
default
(some->> schema m/type (get defaults) (#(% schema)))))
set-default {:compile (fn [schema _]
(if-some [default (get-default schema)]
(when-some [default (get-default schema)]
(fn [x] (if (nil? x) default x))))}
add-defaults {:compile (fn [schema _]
(let [defaults (->> (m/children schema)
(keep (fn [[k {default key} v]]
(if-some [default (if (some? default) default (get-default v))]
[k default])))
(into {}))]
(if (seq defaults)
(let [defaults (into {}
(keep (fn [[k {default key :keys [optional]} v]]
(when-not optional
(when-some [default (if (some? default)
default
(get-default v))]
[k default]))))
(m/children schema))]
(when (seq defaults)
(fn [x]
(if (map? x)
(reduce-kv
Expand Down
6 changes: 6 additions & 0 deletions test/malli/transform_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,12 @@
(is (= {:user/verified false} (m/decode [:map [:user/verified {:default false} boolean?]] {} mt/default-value-transformer)))
(is (= false (m/decode [:and {:default false} boolean?] nil mt/default-value-transformer))))

(testing "optional key"
(is (= {:x 5} (m/decode [:map [:x :int] [:y {:optional true, :default 0} :int]] {:x 5}
mt/default-value-transformer)))
(is (= {:x 5} (m/decode [:map [:x :int] [:y {:optional true} [:int {:default 0}]]] {:x 5}
mt/default-value-transformer))))

(testing "with custom options"
(is (= false (m/decode [:and {:? false} boolean?] nil (mt/default-value-transformer {:key :?}))))
(is (= {:user {:first-name "", :last-name ""}}
Expand Down

0 comments on commit 5193152

Please sign in to comment.