Closed
Description
Is your feature request related to a problem? Please describe.
When using springdoc-openapi in a Kotlin code base, it is annoying that parameters with a nullable type have to be marked manually as optional (required = false
):
@RestController
class MyController{
@GetMapping("/")
fun greet(@RequestParam(required = false) name: String?): String {
if(name != null) return "Hello $name"
return "Hello!"
}
}
Describe the solution you'd like
It would be nice to just leave the required = false
out and just write:
@RestController
class MyController{
@GetMapping("/")
fun greet(@RequestParam name: String?): String {
if(name != null) return "Hello $name"
return "Hello!"
}
}
Describe alternatives you've considered
We were able to achieve this using a ParameterCustomizer. However, I believe that this should be part of springdoc-openapi instead.
@Bean
fun nullableKotlinRequestParameterCustomizer(): ParameterCustomizer {
return ParameterCustomizer { parameterModel, methodParameter ->
if (parameterModel == null) return@ParameterCustomizer null
val kParameter = methodParameter.toKParameter()
if (kParameter != null) {
parameterModel.required = kParameter.type.isMarkedNullable == false
}
return@ParameterCustomizer parameterModel
}
}
private fun MethodParameter.toKParameter(): KParameter? {
// ignore return type, see org.springframework.core.MethodParameter.getParameterIndex
if (parameterIndex == -1) return null
val kotlinFunction = method?.kotlinFunction ?: return null
// The first parameter of the kotlin function is the "this" reference and not needed here.
// See also kotlin.reflect.KCallable.getParameters
return kotlinFunction.parameters[parameterIndex + 1]
}
PS: Thank you for your great work!