Skip to content

Commit

Permalink
Add default-handler support, #37
Browse files Browse the repository at this point in the history
  • Loading branch information
puredanger committed Sep 5, 2019
1 parent a64663e commit 972759a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/cognitect/transit.clj
Original file line number Diff line number Diff line change
Expand Up @@ -146,15 +146,19 @@
with the default-handlers and then with the default handlers
provided by transit-java.
:default-handler - a default WriteHandler to use if NO handler is
found for a type. If no default is specified, an error will be
thrown for an unknown type.
:transform - a function of one argument that will transform values before
they are written."
([out type] (writer out type {}))
([^OutputStream out type {:keys [handlers transform]}]
([^OutputStream out type {:keys [handlers default-handler transform]}]
(if (#{:json :json-verbose :msgpack} type)
(let [handler-map (if (instance? HandlerMapContainer handlers)
(handler-map handlers)
(merge default-write-handlers handlers))]
(Writer. (TransitFactory/writer (transit-format type) out handler-map nil
(Writer. (TransitFactory/writer (transit-format type) out handler-map default-handler
(when transform
(reify Function
(apply [_ x]
Expand Down
25 changes: 25 additions & 0 deletions test/transit/test_handlers.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
(ns transit.test-handlers
(:require [clojure.test :refer [deftest is run-tests]]
[cognitect.transit :as t])
(:import [java.io ByteArrayInputStream ByteArrayOutputStream]))

(defrecord R [a])

(deftest test-no-default
;; no default handler: throws
(is (thrown? Exception
(let [out (ByteArrayOutputStream. 4096)
writer (t/writer out :json)]
(t/write writer (atom 1)))))

;; add default handler: succeeds
(let [out (ByteArrayOutputStream. 4096)
default-handler (t/write-handler
(fn [_] "atom")
(fn [a] @a))
writer (t/writer out :json {:default-handler default-handler})]
(t/write writer (atom 1))))

(comment
(run-tests)
)

0 comments on commit 972759a

Please sign in to comment.