Skip to content

Commit

Permalink
Merge pull request #927 from handerpeder/master
Browse files Browse the repository at this point in the history
add :default/fn prop for default-value-transformer
  • Loading branch information
ikitommi committed Aug 10, 2023
2 parents 8f30b58 + 789db26 commit fee1f17
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/malli/transform.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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))))}
Expand Down
6 changes: 5 additions & 1 deletion test/malli/transform_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -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))))
Expand Down

0 comments on commit fee1f17

Please sign in to comment.