commonMain.me.nathanfallet.ktorx.extensions.OpenAPIExtension.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ktor-routers-jvm Show documentation
Show all versions of ktor-routers-jvm Show documentation
Generic routers for Ktor projects.
package me.nathanfallet.ktorx.extensions
import io.ktor.http.*
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.Operation
import io.swagger.v3.oas.models.PathItem
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.media.Content
import io.swagger.v3.oas.models.media.MediaType
import io.swagger.v3.oas.models.media.Schema
import io.swagger.v3.oas.models.parameters.RequestBody
import io.swagger.v3.oas.models.responses.ApiResponse
import io.swagger.v3.oas.models.responses.ApiResponses
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.elementNames
import kotlinx.serialization.serializer
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.memberProperties
import kotlin.reflect.typeOf
private fun refSchema(type: KType): Schema {
var loop = Pair(type, Schema().`$ref`("#/components/schemas/${type.underlyingType}"))
while (loop.first.isList) {
loop = Pair(
loop.first.arguments.firstOrNull()?.type ?: typeOf(),
Schema>().type("array").items(loop.second).apply {
nullable = loop.first.isMarkedNullable
}
)
}
return loop.second
}
fun OpenAPI.info(build: Info.() -> Unit): OpenAPI = info(
(info ?: Info()).apply(build)
)
@OptIn(ExperimentalSerializationApi::class)
fun OpenAPI.schema(type: KType): Schema {
// List and maps
if (type.isList) return Schema>().type("array").items(
schema(type.arguments.firstOrNull()?.type ?: typeOf())
)
if (type.isSubtypeOf(typeOf