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

org.http4k.contract.openapi.ApiRenderer.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.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) }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy