All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lithic.api.services.HttpRequestBodies.kt Maven / Gradle / Ivy

@file:JvmName("HttpRequestBodies")

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.OutputStream
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder

internal inline fun  json(
    jsonMapper: JsonMapper,
    value: T,
): HttpRequestBody {
    return object : HttpRequestBody {
        override fun writeTo(outputStream: OutputStream) {
            try {
                return jsonMapper.writeValue(outputStream, value)
            } catch (e: Exception) {
                throw LithicException("Error writing request", e)
            }
        }

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

        override fun repeatable(): Boolean = true

        override fun close() {}
    }
}

internal fun multipartFormData(
    files: Map,
): HttpRequestBody {
    val builder = MultipartEntityBuilder.create()
    files.forEach { file, bytes -> builder.addBinaryBody(file, bytes) }
    val entity = builder.build()

    return object : HttpRequestBody {
        override fun writeTo(outputStream: OutputStream) {
            try {
                return entity.writeTo(outputStream)
            } catch (e: Exception) {
                throw LithicException("Error writing request", e)
            }
        }

        override fun contentType(): String = entity.contentType

        override fun repeatable(): Boolean = entity.isRepeatable

        override fun close() = entity.close()
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy