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 006ae1a
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)
(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 006ae1a

Please sign in to comment.