Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add :default/fn prop for default-value-transformer #927

Merged
merged 1 commit into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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