Skip to content

Commit

Permalink
add :default/fn prop for default-value-transformer
Browse files Browse the repository at this point in the history
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)
```
  • Loading branch information
handerpeder committed Aug 9, 2023
1 parent 8f30b58 commit fa74555
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
9 changes: 5 additions & 4 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 All @@ -409,7 +410,7 @@
(when (or (not optional) add-optional-keys)
(let [e (find p key)]
(when-some [f (if e (constantly (val e))
(get-default v))]
(get-default v))]
[k (fn [] (default-fn schema (f)))])))))
(m/children schema))]
(when (seq defaults)
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 fa74555

Please sign in to comment.