Last active
April 8, 2021 02:16
-
-
Save 1gravity/a3d8aa9af044241870b7cae09ce4767d to your computer and use it in GitHub Desktop.
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
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