You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hey, sure, it's possible with octopus.
I'm guessing you have some base trait and few case classes extending it.
sealed trait Person {
def id: Int
def name: String
}
case class Employee(id: Int, name: String, salary: Long) extends Person
case class Employer(id: Int, name: String, employees: List[Employee]) extends Person
Let's define validators for base trait and compose them with rules for case classes.
import octopus.dsl._
implicit val personValidator: Validator[Person] = Validator[Person]
.rule(_.id > 0, "id must be greater than 0")
.rule(_.name.trim.nonEmpty, "name must not be empty")
implicit val employeeValidator: Validator[Employee] = Validator[Employee]
.composeSuper(personValidator)
.rule(_.salary >= 10000, "salary must be at least 10000!")
implicit val employerValidator: Validator[Employer] = Validator[Employer]
.composeSuper(personValidator) // employer is also a person, so it validate its id and name
.composeDerived // composing derived validator for list of employees
See how they work.
import octopus.syntax._
val badEmployee = Employee(0, "", 500)
badEmployee.validate
// invalid:
// : id must be greater than 0
// : name must not be empty
// : salary must be at least 10000!
val goodEmployee = Employee(3, "John", 15000)
goodEmployee.validate
// valid
val badEmployer = Employer(-5, "", List(badEmployee))
badEmployer.validate
// invalid:
// : id must be greater than 0
// : name must not be empty
// employees[0]: id must be greater than 0
// employees[0]: name must not be empty
// employees[0]: salary must be at least 10000!
val goodEmployer = Employer(5, "Mike", List(goodEmployee))
goodEmployer.validate
// valid
Maybe inherit from a base rule?
What I want is not to repeat the same rules in multiple validators.
The text was updated successfully, but these errors were encountered: