Created
June 21, 2013 22:35
-
-
Save andrewconner/5834845 to your computer and use it in GitHub Desktop.
Validating objects during a db save using `Try`
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
case class Employee(id: Option[Long] = None, name: String, age: Int, salary: Int) | |
object EmployeeRepo { | |
private def persist(employee: Employee): Employee = { | |
// persisting logic | |
employee.copy(id = Some(10L)) // database returns persisted id, return new object with id set | |
} | |
def save(employees: Seq[Employee])(implicit validator: Employee => Try[Employee]): Seq[Try[Employee]] = { | |
employees.map(validator(_).map(persist)) | |
} | |
} | |
sealed trait ValidationException extends Throwable { val message: String } | |
case class BadNameException(message: String) extends ValidationException | |
implicit val employeeValidator = { employee: Employee => | |
// validate your object, returning a Success or Failure | |
if(employee.name == "George") Failure(BadNameException("No George's allowed")) | |
else Success(employee) | |
} | |
val employeesToPersist: Seq[Employee] = ... | |
EmployeeRepo.save(employeesToPersist) // : Seq[Try[Employee]], which you can iterate through and deal with problems. | |
// http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#scala.util.Try | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment