Skip to content

Commit

Permalink
feat: add HttpRequestBody.contentLength() (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-app[bot] authored Mar 13, 2024
1 parent 2158ad3 commit 21d5a9e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,17 @@ private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val

private fun HttpRequestBody.toRequestBody(): RequestBody {
val mediaType = contentType()?.toMediaType()
val length = contentLength()

return object : RequestBody() {
override fun contentType(): MediaType? {
return mediaType
}

override fun contentLength(): Long {
return length
}

override fun isOneShot(): Boolean {
return !repeatable()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ interface HttpRequestBody : Closeable {

fun contentType(): String?

fun contentLength(): Long

/**
* Determines if a request can be repeated in a meaningful way, for example before doing a
* retry.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package com.lithic.api.services
import com.fasterxml.jackson.databind.json.JsonMapper
import com.lithic.api.core.http.HttpRequestBody
import com.lithic.api.errors.LithicException
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder

Expand All @@ -13,16 +14,31 @@ internal inline fun <reified T> json(
value: T,
): HttpRequestBody {
return object : HttpRequestBody {
override fun writeTo(outputStream: OutputStream) {
private var cachedBytes: ByteArray? = null

private fun serialize(): ByteArray {
if (cachedBytes != null) return cachedBytes!!

val buffer = ByteArrayOutputStream()
try {
return jsonMapper.writeValue(outputStream, value)
jsonMapper.writeValue(buffer, value)
cachedBytes = buffer.toByteArray()
return cachedBytes!!
} catch (e: Exception) {
throw LithicException("Error writing request", e)
}
}

override fun writeTo(outputStream: OutputStream) {
outputStream.write(serialize())
}

override fun contentType(): String = "application/json"

override fun contentLength(): Long {
return serialize().size.toLong()
}

override fun repeatable(): Boolean = true

override fun close() {}
Expand All @@ -47,6 +63,8 @@ internal fun multipartFormData(

override fun contentType(): String = entity.contentType

override fun contentLength(): Long = -1

override fun repeatable(): Boolean = entity.isRepeatable

override fun close() = entity.close()
Expand Down

0 comments on commit 21d5a9e

Please sign in to comment.