Hi! I have a question concerning response transfor...
# ktor
n
Hi! I have a question concerning response transformation (or rather response capture for idempotency/caching purposes). I tried implementing this example, however my
data
coming from the transformBody is always an instance of
OutgoingContent
or
OutputStreamContent
. I use jackson for serialization, could that be the reason I am unable to capture json?
a
By default, the
JacksonConverter
uses
OutputStreamContent
class as a response body. If the JSON data your server responds with is relatively small, you can turn off body streaming to respond with a
TextContent
that has the
text
property of type
String
.
Copy code
install(ContentNegotiation) {
    jackson(streamRequestBody = false)
}
n
it's a wide variety of responses that can be cached, some big, some small. Is there any document on the correct way to capture the json from the OutputStreamContent?
a
Unfortunately, there is no such document. Here is an example of how you can read the response body of type
OutputStreamContent
while leaving the original body unconsumed:
Copy code
val plugin = createApplicationPlugin("plugin") {
    onCallRespond { call ->
        transformBody { data ->
            if (data is OutputStreamContent) {
                val channel = ByteChannel()

                call.launch {
                    data.writeTo(channel)
                    channel.close()
                }

                val (origChannel, newChannel) = channel.split(call)

                // Read JSON
                println(newChannel.readRemaining().readText())

                origChannel
            } else {
                data
            }
        }
    }
}
n
Thanks, I will give it a try 🙌