簡體   English   中英

過濾和混合Slick中的monad以獲得理解力和Cats

[英]Filtering and mixing monads in Slick for comprehension and Cats

我的目標如下:創建一個向用戶添加以下計算流程的monad:

  1. 檢查用戶是否存在指定的電子郵件, 如果不存在,則:
  2. 檢查給定的憑據是否正確(密碼足夠長等)。 如果還可以,則:
  3. 將用戶保存到數據庫

我的第一個“草稿”將是這樣的:

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://groups.google.com/forum/?fromgroups#!topic/scalaquery/HrvrvyEIopw編寫了一個簡單的隱式dbioMonad。

這不是用於理解的,所以讓我知道是否可以接受。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM