Does someone have a snippet of code to share, showing aleph.http/request
client transformation with muuntaja
encoding? Something that goes from :body-params -> muuntaja/encode :json -> http -> muuntaja/decode :json
and handles content-type
, accept
headers, etc?
I’ve got a server-side example working with reitit
and muuntaja
, but I’m struggling with an end-to-end example on the client side. This doesn’t seem like something I would need to write custom-handling for, but I’m having trouble wiring up the middleware correctly to have it handled automatically.
@pithyless have you tried muuntaja.core/decode-response-body
? It takes a (ring) response and parses the body based on the negotiation headers.
(-> {:headers {"accept" "application/edn"}}
((middleware/wrap-format
(constantly {:status 200, :body {:date (Date. 0)}})))
(m/decode-response-body))
; {:date #inst"1970-01-01T00:00:00.000-00:00"}
with JSON, you need to apply coercion yourself (e.g. strings to dates), but if the client knows the return schema/spec, tooling will give the transformation code for free
@ikitommi so far I’ve got something along the lines of:
@(defer/chain
(http/request opts)
:body
#(stream/map byte-streams/to-byte-array %)
#(stream/reduce conj [] %)
byte-streams/to-string
#(muuntaja/decode "application/json" %))
I can’t use decode-response-body
directly:
No implementation of method: :into-input-stream of protocol: #'muuntaja.protocols/IntoInputStream found for class: manifold.stream.BufferedStream
I can of course write helper methods around the encoders; just seems I’m missing some kind of obvious helper methods and going about this all wrong.
Oh, I see. Two things here: 1) the decode will force the data to be an InputStream
. Muuntaja should allow other types too (encode supports streams, byte-arrays and lazy writers. Will write an issue out of this
2) you can now just extend the muuntaja.protocols/IntoInputStream
to support Manifold Streams
Examples here: https://github.com/metosin/muuntaja/blob/master/modules/muuntaja/src/muuntaja/protocols.clj
after that, the decode-request-body
works.
could be a default mapping there, guarded by the util/when-ns
...
ping @pithyless
thanks for the detailed info 🙂