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

org.http4k.format.ConfigurableJacksonYaml.kt Maven / Gradle / Ivy

package org.http4k.format

import com.fasterxml.jackson.databind.ObjectMapper
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion.TEXT_YAML
import org.http4k.core.HttpMessage
import org.http4k.core.with
import org.http4k.lens.BiDiBodyLensSpec
import org.http4k.lens.BiDiMapping
import org.http4k.lens.ContentNegotiation
import org.http4k.lens.ContentNegotiation.Companion.None
import org.http4k.lens.string
import org.http4k.websocket.WsMessage
import java.io.InputStream
import kotlin.reflect.KClass

open class ConfigurableJacksonYaml(val mapper: ObjectMapper, override val defaultContentType: ContentType = TEXT_YAML) :
    AutoMarshalling() {

    override fun  asA(input: String, target: KClass): T = mapper.readValue(input, target.java)
    override fun  asA(input: InputStream, target: KClass): T = mapper.readValue(input, target.java)

    override fun asFormatString(input: Any): String = mapper.writeValueAsString(input)

    override fun asInputStream(input: Any): InputStream = mapper.writeValueAsBytes(input).inputStream()

    inline fun  WsMessage.Companion.auto() = WsMessage.string().map(mapper.read(), mapper.write())

    inline fun  asBiDiMapping() = BiDiMapping>(mapper.read(), mapper.write())

    inline fun  Body.Companion.auto(
        description: String? = null,
        contentNegotiation: ContentNegotiation = None
    ) = autoBody(description, contentNegotiation)

    inline fun  autoBody(
        description: String? = null,
        contentNegotiation: ContentNegotiation = None
    ): BiDiBodyLensSpec =
        httpBodyLens(description, contentNegotiation, defaultContentType).map(mapper.read(), mapper.write())

    /**
     * Convenience function to write the object as YAML to the message body and set the content type.
     */
    inline fun  R.yaml(t: T): R = with(Body.auto().toLens() of t)

    /**
     * Convenience function to read an object as YAML from the message body.
     */
    inline fun  HttpMessage.yaml(): T = Body.auto().toLens()(this)
}

inline operator fun  ConfigurableJacksonYaml.invoke(msg: HttpMessage): T = autoBody().toLens()(msg)
inline operator fun  ConfigurableJacksonYaml.invoke(item: T) = autoBody().toLens().of(item)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy