Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,76 @@ compile "cc.vileda:kotlin-openapi3-dsl:1.5.0"

for a complete example [look at the test](src/test/kotlin/cc/vileda/openapi/dsl/OpenApiDslTest.kt)

### reusable components

The `components` block supports every OpenAPI 3.0 component type: schemas,
responses, parameters, examples, request bodies, headers, security schemes,
links, and callbacks. Reference helpers accept component names and create the
canonical `#/components/...` reference:

```kotlin
components {
parameter("PageSize") {
name = "pageSize"
`in` = "query"
}
response("NotFound") {
description = "resource not found"
}
}

paths {
path("/items") {
get {
parameterRef("PageSize")
responses {
responseRef("404", "NotFound")
}
}
}
}
```

### recursive schemas

`mediaTypeRef<T>()` and `mediaTypeArrayOfRef<T>()` automatically add `T` and
all transitively referenced models to `components.schemas`. An explicit
components block is not required:

```kotlin
data class ErrorDetail(val message: String)
data class ErrorResponse(val detail: ErrorDetail)

content {
mediaTypeRef<ErrorResponse>("application/json")
}
```

`components { schema<T>() }` also registers transitive models. Explicit schema
customisations take precedence over automatically discovered schemas.

### Kotlin required properties

Required-property inference is disabled by default. Enable it for one DSL build:

```kotlin
openapiDsl(
OpenApiDslConfig(inferRequiredFromKotlinNullability = true)
) {
// ...
}
```

Non-null Kotlin primary-constructor properties without default values are then
added to the schema's `required` list. Nullable and defaulted properties remain
optional. Explicit Swagger `requiredMode` annotations take precedence.

## output

`asJsonString()` and `asFile()` preserve the insertion order used by the DSL.
Use `asJsonString(pretty = true)` for formatted JSON without writing a file.
`asJson()` returns a `JSONObject`, whose key order is intentionally unspecified.

## license
```
Copyright 2017 Tristan Leo
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ apply plugin: 'maven-publish'
apply plugin: 'signing'

group 'cc.vileda'
version '1.5.0'
version '1.6.0'

repositories {
mavenCentral()
Expand Down
69 changes: 69 additions & 0 deletions src/main/kotlin/cc/vileda/openapi/dsl/ComponentsDsl.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cc.vileda.openapi.dsl

import io.swagger.v3.oas.models.Components
import io.swagger.v3.oas.models.Operation
import io.swagger.v3.oas.models.callbacks.Callback
import io.swagger.v3.oas.models.examples.Example
import io.swagger.v3.oas.models.headers.Header
import io.swagger.v3.oas.models.links.Link
import io.swagger.v3.oas.models.media.MediaType
import io.swagger.v3.oas.models.parameters.Parameter
import io.swagger.v3.oas.models.parameters.RequestBody
import io.swagger.v3.oas.models.responses.ApiResponse
import io.swagger.v3.oas.models.responses.ApiResponses

fun Components.response(name: String, init: ApiResponse.() -> Unit) {
addResponses(name, ApiResponse().apply(init))
}

fun Components.parameter(name: String, init: Parameter.() -> Unit) {
addParameters(name, Parameter().apply(init))
}

fun Components.example(name: String, init: Example.() -> Unit) {
addExamples(name, Example().apply(init))
}

fun Components.requestBody(name: String, init: RequestBody.() -> Unit) {
addRequestBodies(name, RequestBody().apply(init))
}

fun Components.header(name: String, init: Header.() -> Unit) {
addHeaders(name, Header().apply(init))
}

fun Components.link(name: String, init: Link.() -> Unit) {
addLinks(name, Link().apply(init))
}

fun Components.callback(name: String, init: Callback.() -> Unit) {
addCallbacks(name, Callback().apply(init))
}

fun Operation.parameterRef(name: String) {
addParametersItem(Parameter().apply { `$ref` = name })
}

fun ApiResponses.responseRef(status: String, name: String) {
addApiResponse(status, ApiResponse().apply { `$ref` = name })
}

fun Operation.requestBodyRef(name: String) {
requestBody = RequestBody().apply { `$ref` = name }
}

fun MediaType.exampleRef(name: String, componentName: String = name) {
addExamples(name, Example().apply { `$ref` = componentName })
}

fun ApiResponse.headerRef(name: String, componentName: String = name) {
addHeaderObject(name, Header().apply { `$ref` = componentName })
}

fun ApiResponse.linkRef(name: String, componentName: String = name) {
addLink(name, Link().apply { `$ref` = componentName })
}

fun Operation.callbackRef(name: String, componentName: String = name) {
addCallback(name, Callback().apply { `$ref` = componentName })
}
121 changes: 121 additions & 0 deletions src/main/kotlin/cc/vileda/openapi/dsl/KotlinRequiredProperties.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package cc.vileda.openapi.dsl

import com.fasterxml.jackson.annotation.JsonProperty
import io.swagger.v3.oas.annotations.media.Schema as SchemaAnnotation
import io.swagger.v3.oas.models.media.Schema
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.KProperty1
import kotlin.reflect.KType
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.javaField
import kotlin.reflect.jvm.javaGetter

internal fun inferRequiredProperties(
rootType: Class<*>,
rootName: String,
schemas: Map<String, Schema<*>>
) {
RequiredPropertyInference(schemas).visit(rootType.kotlin, rootName)
}

private class RequiredPropertyInference(
private val schemas: Map<String, Schema<*>>
) {
private val visited = mutableSetOf<KClass<*>>()

fun visit(type: KClass<*>, schemaName: String? = null) {
if (!visited.add(type) || type.java.getAnnotation(Metadata::class.java) == null) return

val schema = schemas[schemaName ?: componentName(type)] ?: return
val properties = type.memberProperties.associateBy { it.name }
val constructor = type.primaryConstructor ?: return

constructor.parameters
.filter { it.kind == KParameter.Kind.VALUE }
.forEach { parameter ->
val property = parameter.name?.let(properties::get)
val annotations = schemaAnnotations(parameter, property)
val propertyName = schemaPropertyName(parameter, property, schema, annotations)
if (propertyName != null && shouldBeRequired(parameter, annotations)) {
if (schema.required?.contains(propertyName) != true) {
schema.addRequiredItem(propertyName)
}
}
visitNestedTypes(parameter.type)
}
}

private fun visitNestedTypes(type: KType) {
val classifier = type.classifier as? KClass<*> ?: return
val javaType = classifier.java
if (!javaType.isArray &&
!Iterable::class.java.isAssignableFrom(javaType) &&
!Map::class.java.isAssignableFrom(javaType)
) {
visit(classifier)
}
type.arguments.forEach { argument -> argument.type?.let(::visitNestedTypes) }
}

private fun schemaPropertyName(
parameter: KParameter,
property: KProperty1<out Any, *>?,
schema: Schema<*>,
annotations: List<SchemaAnnotation>
): String? {
val declaredName = parameter.name ?: return null
val candidates = buildList {
jsonPropertyNames(parameter, property).forEach(::add)
annotations.mapNotNullTo(this) { it.name.takeIf(String::isNotBlank) }
add(declaredName)
}
return candidates.firstOrNull { schema.properties?.containsKey(it) == true }
}

private fun shouldBeRequired(
parameter: KParameter,
annotations: List<SchemaAnnotation>
): Boolean {
return when (annotations
.map { it.requiredMode }
.firstOrNull { it != SchemaAnnotation.RequiredMode.AUTO }) {
SchemaAnnotation.RequiredMode.REQUIRED -> true
SchemaAnnotation.RequiredMode.NOT_REQUIRED -> false
else -> !parameter.type.isMarkedNullable && !parameter.isOptional
}
}

private fun schemaAnnotations(
parameter: KParameter,
property: KProperty1<out Any, *>?
): List<SchemaAnnotation> {
return listOfNotNull(
parameter.findAnnotation(),
property?.findAnnotation(),
property?.javaField?.getAnnotation(SchemaAnnotation::class.java),
property?.javaGetter?.getAnnotation(SchemaAnnotation::class.java)
)
}

private fun jsonPropertyNames(
parameter: KParameter,
property: KProperty1<out Any, *>?
): List<String> {
return listOfNotNull(
parameter.findAnnotation<JsonProperty>()?.value,
property?.findAnnotation<JsonProperty>()?.value,
property?.javaField?.getAnnotation(JsonProperty::class.java)?.value,
property?.javaGetter?.getAnnotation(JsonProperty::class.java)?.value
).filter(String::isNotBlank)
}

private fun componentName(type: KClass<*>): String {
return type.java.getAnnotation(SchemaAnnotation::class.java)
?.name
?.takeIf(String::isNotBlank)
?: type.java.simpleName
}
}
Loading