我有以下目标:
创建一个添加用户的 monad,计算流程如下:
- 检查是否存在具有指定电子邮件的用户,如果他不这样做 then :
- 检查所提供的凭据是否正确(密码足够长等)。如果他们没问题,那么:
- 将用户保存到数据库
我的第一个“草稿”是这样的:
val work: DBIO[UserId] = for {
userO <- UserRepository.findByEmail(createdUser.email) //userO is Option[User]
//This won't work cause Action.withFilter doesnt exist
if userO.isEmpty
//as above, validate user actually returns an ValidateNel[String, User]
if User.validateUser(createdUser.email, createdUser.password).isValid
//Returns DBIO[UserId]
id <- UserRepository.save(createdUser)
} yield id
有什么想法可以用 db.run(...) 的一元计算写下这一点的最佳方法吗?我正在使用 Cats + Slick 3.0。
我还写了一个简单的隐式 dbioMonadhttps://groups.google.com/forum/?fromgroups#!topic/scalaquery/HrvrvyEIopw https://groups.google.com/forum/?fromgroups#!topic/scalaquery/HrvrvyEIopw如果有帮助的话。
这并不用于理解,所以请告诉我这是否可以接受。
val work: DBIO[UserId] = {
UserRepository.findByEmail(createdUser.email).flatMap {
case Some(_) => DBIO.failed(new Exception("Provided email is already taken"))
case _ =>
if(User.validateUser(createdUser.email, createdUser.password).isValid) {
UserRepository.save(createdUser)
} else {
DBIO.failed(new Exception("User validation has failed"))
}
}.transactionally
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)