Skip to content

Instantly share code, notes, and snippets.

@dcalsky
Created March 31, 2020 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcalsky/f380e7861392ee875e786d67616b49a9 to your computer and use it in GitHub Desktop.
Save dcalsky/f380e7861392ee875e786d67616b49a9 to your computer and use it in GitHub Desktop.
Ktor json validation with Hibernate Validator
// Convert application-json content to DTO with validation and rasing error message
suspend inline fun <reified T : Any> ApplicationCall.bindJson(): T {
val dto = this.receive<T>()
val violations = validator.validate(dto);
if (violations.size > 0) {
// Throw error messages when found violdations
val details = violations.map {
val propertyName = it.propertyPath.toString()
val errorMessage = it.message
"${propertyName}: $errorMessage"
}
// Your custom Exception in Status Page feature of Ktor application
throw CustomException(details)
} else {
return dto
}
}
// A sample Dto model
// Define constraints for Dto
data class ConsumingRequestDto(
@get:Positive // Do not declear `NotNull` because jackson will fill `0` to missing Int field
val idolId: Int, // Yep, I like idol
@get:Min(10, message = "最少投入10守护星") // Custom Chinese error message
val star: Int
)
// A sample route
// Let create some consuming for our idol.
route("consumings") {
authenticate {
post {
// Validate request data and raise exceptions (or not)
val dto = call.bindJson<ConsumingRequestDto>()
call.respond(dto)
}
}
}
@dcalsky
Copy link
Author

dcalsky commented Mar 31, 2020

I think it's the best and simplest validation solution for personal project that uses Ktor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment