From 789db265009e6bacd2b09527e4aab0f7118b603e Mon Sep 17 00:00:00 2001 From: Peder Refsnes Date: Wed, 9 Aug 2023 22:30:17 +0200 Subject: [PATCH] add :default/fn prop for default-value-transformer use case: we want the default value to be current time. previously you would have to do something like this: ``` (m/decode [:time/instant {:default :now}] nil (mt/default-value-transformer {:default-fn (fn [_ x ] (case x :now (java.time.Instant/now) x))})) ``` this patch lets you declare this without the indirection: ``` (m/decode [:time/instant {:default/fn #(java.time.Instant/now)}] nil mt/default-value-transformer) ``` --- src/malli/transform.cljc | 7 ++++--- test/malli/transform_test.cljc | 6 +++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/malli/transform.cljc b/src/malli/transform.cljc index 33aa8b711..e7e4a1e63 100644 --- a/src/malli/transform.cljc +++ b/src/malli/transform.cljc @@ -397,9 +397,10 @@ ([] (default-value-transformer nil)) ([{:keys [key default-fn defaults ::add-optional-keys] :or {key :default, default-fn (fn [_ x] x)}}] (let [get-default (fn [schema] - (if-some [e (some-> schema m/properties (find key))] - (constantly (val e)) - (some->> schema m/type (get defaults) (#(constantly (% schema)))))) + (or (some-> schema m/properties :default/fn m/eval) + (if-some [e (some-> schema m/properties (find key))] + (constantly (val e)) + (some->> schema m/type (get defaults) (#(constantly (% schema))))))) set-default {:compile (fn [schema _] (when-some [f (get-default schema)] (fn [x] (if (nil? x) (default-fn schema (f)) x))))} diff --git a/test/malli/transform_test.cljc b/test/malli/transform_test.cljc index 3d7b7e468..15b2e5936 100644 --- a/test/malli/transform_test.cljc +++ b/test/malli/transform_test.cljc @@ -971,7 +971,11 @@ seen (atom []) transformer (mt/default-value-transformer {:key :name, :default-fn (fn [_ x] (swap! seen conj x) x)})] (is (= {:first 'one, :second 'two} (m/encode schema {} transformer))) - (is (= ['one 'two] @seen)))))) + (is (= ['one 'two] @seen))))) + + (testing ":default/fn property on schema" + (let [schema [:string {:default/fn (fn [] "called")}]] + (is (= "called" (m/decode schema nil mt/default-value-transformer)))))) (deftest type-properties-based-transformations (is (= 12 (m/decode malli.core-test/Over6 "12" mt/string-transformer))))