org.http4k.contract.openapi.ApiRenderer.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.openapi.v3.AutoJsonToJsonSchema
import org.http4k.contract.openapi.v3.JsonToJsonSchema
import org.http4k.format.AutoMarshallingJson
import org.http4k.util.JsonSchema
import org.http4k.util.JsonSchemaCreator
import java.util.concurrent.atomic.AtomicReference
/**
* Renders the contract contents in OpenApi JSON format.
*/
interface ApiRenderer : JsonSchemaCreator {
fun api(api: API): NODE
companion object {
/**
* ApiRenderer which uses auto-marshalling JSON to create JSON schema for message models.
*/
fun Auto(
json: AutoMarshallingJson,
schema: JsonSchemaCreator = AutoJsonToJsonSchema(json)): ApiRenderer {
val fallbackSchema = object : JsonSchemaCreator {
private val jsonNodes = JsonToJsonSchema(json)
override fun toSchema(obj: Any, overrideDefinitionId: String?, refModelNamePrefix: String?): JsonSchema =
try {
@Suppress("UNCHECKED_CAST")
jsonNodes.toSchema(obj as NODE, overrideDefinitionId, refModelNamePrefix)
} catch (e: ClassCastException) {
schema.toSchema(obj, overrideDefinitionId, refModelNamePrefix)
}
}
return object : ApiRenderer, JsonSchemaCreator by fallbackSchema {
override fun api(api: T) = json.asJsonObject(api)
}
}
}
}
/**
* Cache the result of the API render, in case it is expensive to calculate.
*/
fun ApiRenderer.cached(): ApiRenderer = object : ApiRenderer by this {
private val cached = AtomicReference()
override fun api(api: API): NODE = cached.get() ?: [email protected](api).also { cached.set(it) }
}