
org.http4k.lens.Validator.kt Maven / Gradle / Ivy
package org.http4k.lens
/**
* Runs through a list of lenses and extracts the values from each one, collecting the errors
*/
enum class Validator(private val actOn: (LensFailure) -> List) {
Strict({ if (it.failures.isNotEmpty()) throw it else it.failures }),
Feedback({ it.failures }),
Ignore({ emptyList() });
operator fun invoke(entity: T, lenses: List>): List =
collectErrors(lenses, entity).run {
actOn(when (size) {
0 -> LensFailure()
1 -> first()
else -> LensFailure(flatMap { it.failures }, LensFailures(this), entity)
})
}
private fun collectErrors(lenses: List>, entity: T): List =
lenses.fold(emptyList()) { memo, next ->
try {
next(entity)
memo
} catch (e: LensFailure) {
memo + e
}
}
}
data class LensFailures(val causes: List) : RuntimeException()
© 2015 - 2025 Weber Informatics LLC | Privacy Policy