org.http4k.contract.openapi.SecurityRenderer.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of http4k-contract Show documentation
Show all versions of http4k-contract Show documentation
http4k typesafe HTTP contracts and OpenApi support
package org.http4k.contract.openapi
import org.http4k.contract.security.AndSecurity
import org.http4k.contract.security.OrSecurity
import org.http4k.contract.security.Security
/**
* Provides rendering of Security models in to OpenApi specs.
*/
interface SecurityRenderer {
fun full(security: Security): Render?
fun ref(security: Security): Render?
companion object {
operator fun invoke(vararg renderers: SecurityRenderer): SecurityRenderer = object : SecurityRenderer {
override fun full(security: Security): Render? = when (security) {
is AndSecurity -> security.renderAll { full(it) }?.toObj()
is OrSecurity -> security.renderAll { full(it) }?.toObj()
else -> renderers.asSequence().mapNotNull { it.full(security) }.firstOrNull()
}
override fun ref(security: Security): Render? = when (security) {
is AndSecurity -> security.renderAll { ref(it) }?.toObj()
is OrSecurity -> security.renderAll { ref(it) }?.toArray()
else -> renderers.asSequence().mapNotNull { it.ref(security) }.firstOrNull()
}
private fun Iterable.renderAll(transform: (Security) -> Render?) =
mapNotNull(transform).takeIf { it.isNotEmpty() }
private fun List>.toObj(): Render = {
obj(flatMap { fields(it(this)) })
}
private fun List>.toArray(): Render = {
array(flatMap { fields(it(this)) }.map { obj(it) })
}
}
}
}
interface RenderModes {
fun full(): Render
fun ref(): Render
}
inline fun rendererFor(crossinline fn: (T) -> RenderModes) = object : SecurityRenderer {
override fun full(security: Security): Render? = if (security is T) fn(security).full() else null
override fun ref(security: Security): Render? = if (security is T) fn(security).ref() else null
}