Skip to content

Instantly share code, notes, and snippets.

@1gravity
Last active April 8, 2021 02:16
Show Gist options
  • Save 1gravity/a3d8aa9af044241870b7cae09ce4767d to your computer and use it in GitHub Desktop.
Save 1gravity/a3d8aa9af044241870b7cae09ce4767d to your computer and use it in GitHub Desktop.
val uuidRegex = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$".toRegex()
data class Account(
var accountUUID: String,
var createdAt: Instant,
var modifiedAt: Instant,
var status: AccountStatus
) {
init {
runCatching {
validate(this) {
validate(Account::accountUUID).matches(uuidRegex)
validate(Account::createdAt).isNotNull()
validate(Account::modifiedAt).isNotNull()
validate(Account::status).isNotNull()
}
}.throwOnFailure()
}
}
fun <T> Result<T>.throwOnFailure() {
if (isFailure) {
throw IllegalArgumentException((exceptionOrNull() as ConstraintViolationException).getMessage())
}
}
fun ConstraintViolationException.getMessage() =
constraintViolations.fold(StringBuilder()) { result, violation ->
val message = violation.toMessage(locale = Locale.ENGLISH)
result.append("${violation.property}: $message")
result
}.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment