Skip to content

Commit

Permalink
Merge pull request #131 from nvlass/edn-pr-str-with-lazy-sequences
Browse files Browse the repository at this point in the history
Logging in lazy sequences may interfere with output of Content-Type: application/edn
  • Loading branch information
opqdonut authored Jan 9, 2025
2 parents 0b60f12 + 4027da7 commit 55a4387
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
6 changes: 4 additions & 2 deletions modules/muuntaja/src/muuntaja/format/edn.clj
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
core/EncodeToBytes
(encode-to-bytes [_ data charset]
(.getBytes
(pr-str data)
^String charset))
(let [w (new java.io.StringWriter)]
(print-method data w)
(.toString w))
^String charset))
core/EncodeToOutputStream
(encode-to-output-stream [_ data charset]
(fn [^OutputStream output-stream]
Expand Down
19 changes: 19 additions & 0 deletions test/muuntaja/ring_middleware/format_response_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,25 @@
;; we do not set the "Content-Length"
#_(is (< 2 (Integer/parseInt (get-in resp [:headers "Content-Length"]))))))

(defn- produce-element-with-log [n]
(prn "reading from db" n)
{:element n})

(defn- dummy-handler-with-lazy-seq [_]
{:status 200
:body (map produce-element-with-log (range 4))})

(deftest lazy-sequences-with-logs
(let [handler (wrap-api-response
dummy-handler-with-lazy-seq
(-> m/default-options
(m/select-formats ["application/edn"])))
resp (handler {})
body (slurp (:body resp))]
;; Lazy sequence realization interferes with `with-out-str`
#_(is (= body "(\"reading from db\" 0\n\"reading from db\" 1\n\"reading from db\" 2\n\"reading from db\" 3\n{:element 0} {:element 1} {:element 2} {:element 3})"))
(is (= body "({:element 0} {:element 1} {:element 2} {:element 3})"))))

(def yaml-echo
(wrap-api-response
identity
Expand Down

0 comments on commit 55a4387

Please sign in to comment.