Skip to content

Commit

Permalink
feat(client): allow binary returns (#114)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed Nov 8, 2023
1 parent 3e120cb commit 1bea317
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.lithic.api.core.http

import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

interface BinaryResponseContent : Closeable {

fun contentType(): String?

fun body(): InputStream

@Throws(IOException::class) fun writeTo(outputStream: OutputStream)
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package com.lithic.api.services

import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import com.lithic.api.core.http.BinaryResponseContent
import com.lithic.api.core.http.HttpResponse
import com.lithic.api.core.http.HttpResponse.Handler
import com.lithic.api.errors.BadRequestException
Expand All @@ -16,6 +17,8 @@ import com.lithic.api.errors.RateLimitException
import com.lithic.api.errors.UnauthorizedException
import com.lithic.api.errors.UnexpectedStatusCodeException
import com.lithic.api.errors.UnprocessableEntityException
import java.io.InputStream
import java.io.OutputStream

@JvmSynthetic internal fun emptyHandler(): Handler<Void?> = EmptyHandler

Expand All @@ -25,12 +28,20 @@ private object EmptyHandler : Handler<Void?> {

@JvmSynthetic internal fun stringHandler(): Handler<String> = StringHandler

@JvmSynthetic internal fun binaryHandler(): Handler<BinaryResponseContent> = BinaryHandler

private object StringHandler : Handler<String> {
override fun handle(response: HttpResponse): String {
return response.body().readBytes().toString(Charsets.UTF_8)
}
}

private object BinaryHandler : Handler<BinaryResponseContent> {
override fun handle(response: HttpResponse): BinaryResponseContent {
return BinaryResponseContentImpl(response)
}
}

@JvmSynthetic
internal inline fun <reified T> jsonHandler(jsonMapper: JsonMapper): Handler<T> {
return object : Handler<T> {
Expand Down Expand Up @@ -96,3 +107,24 @@ internal fun <T> Handler<T>.withErrorHandler(errorHandler: Handler<LithicError>)
}
}
}

class BinaryResponseContentImpl
constructor(
private val response: HttpResponse,
) : BinaryResponseContent {
override fun contentType(): String? {
return response.headers().get("Content-Type").firstOrNull()
}

override fun body(): InputStream {
return response.body()
}

override fun writeTo(outputStream: OutputStream) {
response.body().copyTo(outputStream)
}

override fun close() {
response.body().close()
}
}

0 comments on commit 1bea317

Please sign in to comment.