在Slick中过滤和混合monad以便理解和Cat [英] Filtering and mixing monads in Slick for comprehension and Cats

查看:135
本文介绍了在Slick中过滤和混合monad以便理解和Cat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下目标:
创建一个monad,用以下计算流程添加用户:

I have the following objective: Create a monad that adds an user with the following computation flow:


  1. 检查是否用户存在指定的电子邮件,如果他不存在,则:
  2. 检查给定的凭证是否正确(密码足够长等) 。如果他们没问题,那么:

  3. 将用户保存到数据库中

  1. Check if an user exists with a specified e-mail, if he doesn't then :
  2. Check if the credentials given are ok (password long enough, etc.). If they are ok, then:
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆