在Slick中过滤和混合monad以便理解和Cat [英] Filtering and mixing monads in Slick for comprehension and Cats
问题描述
我有以下目标:
创建一个monad,用以下计算流程添加用户:
I have the following objective: Create a monad that adds an user with the following computation flow:
- 检查是否用户存在指定的电子邮件,如果他不存在,则:
- 检查给定的凭证是否正确(密码足够长等) 。如果他们没问题,那么:
- 将用户保存到数据库中
- Check if an user exists with a specified e-mail, if he doesn't then :
- Check if the credentials given are ok (password long enough, etc.). If they are ok, then:
- Save the user to the DB
草稿将是这样的:
My first "draft" would be something like this:
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。
此外,我还从 https:/ zh_CN写了一个简单的隐式dbioMonad /groups.google.com/forum/?fromgroups#!topic/scalaquery/HrvrvyEIopw ,如果有帮助的话。
Any ideas what is the best way to write this down in one monadic computation that I can db.run(...)? I'm using Cats + Slick 3.0. Also I've wrote a simple implicit dbioMonad from https://groups.google.com/forum/?fromgroups#!topic/scalaquery/HrvrvyEIopw if that helps.
推荐答案
这一个不用于理解,所以让我知道如果这是可以接受的。
This one doesn't use for comprehension, so let me know if that's acceptable.
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
}
这篇关于在Slick中过滤和混合monad以便理解和Cat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!