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

org.http4k.contract.openapi.SecurityRenderer.kt Maven / Gradle / Ivy

There is a newer version: 5.31.0.0
Show newest version
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
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy