我在mongo dao中创建了3个重复检查,以检查数据库中3种不同的重复情况。 (我知道做到这一点的最佳方法是为那些对象创建一个复合索引,但是不幸的是,目前无法实现,我需要那些检查)
所以我想这样做,创建这个方法:
def checkPersonDuplication(person: Person): Future[(ValidationResult, Option[Person])] = for {
sameSocIdIAndCountryVerification <- {
logger.info("sameSocIdIAndCountryVerification is running")
findPersonSameSocIdIAndCountry(person.socId, person.country)
}
sameNameAndCountryVerification <- {
logger.info("sameNameAndCountryVerification is running")
findPersonSameNameAndCountry(person.name, person.country)
}
sameLastNameAndCountryVerification <- {
logger.info("sameLastNameAndCountryVerification is running")
findPersonSameByNameAndCountry(person.lname, person.country)
}
} yield (sameSocIdIAndCountryVerification, sameNameAndCountryVerification, sameLastNameAndCountryVerification) match {
case a if a._1.isDefined => (SameSocialSecurityNumberAndCountry, sameSocIdIAndCountryVerification)
case b if b._2.isDefined => (SameNameAndCountry, sameNameAndCountryVerification)
case c if c._3.isDefined => (SameLastNameAndCountry, sameLastNameAndCountryVerification)
case _ => (ValidationSuccess, None)
}
现在在创建方法中,我可以这样做:
checkPersonDuplication(person) map {res =>
res._1 match {
case ValidationSuccess => // do something
case SameSocialSecurityNumberAndCountry => throw DuplicateInsertion(s"???")
case SameNameAndCountry => throw DuplicateInsertion(s"???")
case SameLastNameAndCountry => throw DuplicateInsertion(s"???")
}
}
我的问题是,如果定义了sameSocIdIAndCountryVerification
(因为findPersonSameSocIdIAndCountry
返回Option [Person]),我不想在理解中运行其他检查...
所以我尝试在每个后面添加“ if”,但它使我NoSuchElementException
丢了。最好的方法是什么?
答案 0 :(得分:0)
此版本避免了不必要的验证,但是它不是特别漂亮:
def checkPersonDuplication(person: Person): Future[(ValidationResult, Option[Person])] = {
logger.info("sameSocIdIAndCountryVerification is running")
findPersonSameSocIdIAndCountry(person.socId, person.country).flatMap {
case x@Some(_) =>
Future.successful((SameSocialSecurityNumberAndCountry, x))
case None =>
logger.info("sameNameAndCountryVerification is running")
findPersonSameNameAndCountry(person.name, person.country).flatMap {
case x@Some(_) =>
Future.successful((SameNameAndCountry, x))
case None =>
logger.info("sameLastNameAndCountryVerification is running")
findPersonSameByNameAndCountry(person.lname, person.country).map {
case x@Some(_) =>
(SameLastNameAndCountry, x)
case None =>
(ValidationSuccess, None)
}
}
}
}