In documentation and code samples of Ktor, regarding RequestValidation plugin (https://ktor.io/docs/request-validation.html) there are validators for different types but all defined on same place, within install(RequestValidation) {}
install(RequestValidation) {
validate<String> { bodyText ->
if (!bodyText.startsWith("Hello"))
ValidationResult.Invalid("Body text should start with 'Hello'")
else ValidationResult.Valid
}
validate<Customer> { customer ->
if (customer.id <= 0)
ValidationResult.Invalid("A customer ID should be greater than 0")
else ValidationResult.Valid
}
validate {
filter { body ->
body is ByteArray
}
validation { body ->
check(body is ByteArray)
val intValue = String(body).toInt()
if (intValue <= 0)
ValidationResult.Invalid("A value should be greater than 0")
else ValidationResult.Valid
}
}
}
Is there a better approach to this? This would not make any sense if we are to validate lots of different request body types. Is there a way to structure these "validators" in separate files/classes and register only once at install(RequestValidation) {}
or something similar?
EDIT: Only other approach I could think of is this:
RequestValidation.kt
fun Application.configureRequestValidation() {
install(RequestValidation) {
validate<RequestBodyType> {
requestBodyTypeValidation(it)
}
}
}
SomeFeatureRouting.kt
fun requestBodyTypeValidation(requestBody: RequestBodyType): ValidationResult {
// Validate requestBody properties here
}
Marginally cleaner but kinda to coupled