0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
lmiskovic
  • 109
  • 1
  • 10
  • 1
    You can define a class for a validator by implementing the `Validator` interface and registering its object within the `RequestValidation` plugin. Can you please explain what's wrong with validating different body types? – Aleksei Tirman Mar 14 '23 at 15:23
  • Yes, that actually looks like better approach. Issue is that defining all validation logic in one place would very soon became messy, imaging having to validate 20 different types with multiple properties. Approach you suggested would allowed me to define it separately for each type which by itself is cleaner. – lmiskovic Mar 14 '23 at 15:47

0 Answers0