Created
March 31, 2020 15:40
-
-
Save dcalsky/f380e7861392ee875e786d67616b49a9 to your computer and use it in GitHub Desktop.
Ktor json validation with Hibernate Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it's the best and simplest validation solution for personal project that uses Ktor.