diff --git a/bidrag-commons/pom.xml b/bidrag-commons/pom.xml index eb8b697b..3328dfbb 100644 --- a/bidrag-commons/pom.xml +++ b/bidrag-commons/pom.xml @@ -148,6 +148,11 @@ bidrag-transport-felles ${project.parent.version} + + org.springdoc + springdoc-openapi-starter-webmvc-ui + provided + io.mockk diff --git a/bidrag-commons/src/main/kotlin/no/nav/bidrag/commons/util/OpenApiExamplesConfig.kt b/bidrag-commons/src/main/kotlin/no/nav/bidrag/commons/util/OpenApiExamplesConfig.kt new file mode 100644 index 00000000..993e36a3 --- /dev/null +++ b/bidrag-commons/src/main/kotlin/no/nav/bidrag/commons/util/OpenApiExamplesConfig.kt @@ -0,0 +1,59 @@ +package no.nav.bidrag.commons.util + +import io.swagger.v3.oas.models.OpenAPI +import io.swagger.v3.oas.models.PathItem +import io.swagger.v3.oas.models.examples.Example +import org.springdoc.core.customizers.OpenApiCustomizer +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.http.HttpMethod +import org.springframework.http.MediaType + +@Configuration +class OpenApiExamplesConfig { + @Bean + fun openApiCustomiser(examples: Collection): OpenApiCustomizer { + return OpenApiCustomizer { openAPI -> + examples.forEach { example -> + openAPI.components.addExamples(example.name, example.example) + examples.groupBy { Pair(it.path, it.method) }.entries.forEach { + openAPI.addExamplesToPath(it.key, it.value) + } + } + } + } + + fun OpenAPI.addExamplesToPath( + operation: Pair, + openApiExamples: List, + ) { + val requestBody = + paths[operation.first]?.getOperation(operation.second) + ?.requestBody + + val jsonBody = requestBody?.content?.get(MediaType.APPLICATION_JSON_VALUE) + + openApiExamples + .forEach { + jsonBody?.addExamples(it.name, it.example) + } + } + + fun PathItem.getOperation(httpMethod: HttpMethod) = + when (httpMethod) { + HttpMethod.POST -> post + HttpMethod.PUT -> put + HttpMethod.PATCH -> patch + HttpMethod.DELETE -> delete + HttpMethod.OPTIONS -> options + HttpMethod.GET -> get + else -> null + } +} + +data class OpenApiExample( + val example: Example, + val method: HttpMethod, + val path: String, + val name: String = example.description, +) diff --git a/pom.xml b/pom.xml index 720490f0..222a31ae 100644 --- a/pom.xml +++ b/pom.xml @@ -22,6 +22,7 @@ 1.13.9 3.2.1 6.0.2 + 2.3.0 3.12.1 @@ -87,7 +88,13 @@ kotlin-logging-jvm ${kotlin-logging-jvm.version} + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc-openapi-ui.version} + + org.jetbrains.kotlin kotlin-test-junit5