diff --git a/src/malli/transform.cljc b/src/malli/transform.cljc index 261662987..17f9364d4 100644 --- a/src/malli/transform.cljc +++ b/src/malli/transform.cljc @@ -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 diff --git a/test/malli/transform_test.cljc b/test/malli/transform_test.cljc index e63a1df1b..9f2dfc521 100644 --- a/test/malli/transform_test.cljc +++ b/test/malli/transform_test.cljc @@ -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 ""}}