2015-12-08 77 views
2

我用油滑3.1代碼生成器來創建默認對象和特質Tables.scala油滑3.1 - 轉換油滑錶行對象,以案例類

下面的方法工作,但是我想隱式或顯式轉換UserRow和PasswordsRow到User和UserPassword。

工作方法:

override def getUser(email: String): Future[Option[(Tables.UsersRow, Tables.PasswordsRow)]] = db.run { 
(for { 
    user <- users if user.email === email 
    password <- passwords if password.id === user.id 
} yield (user, password)).result.headOption 

}

期望的方法:

package model 

import com.wordnik.swagger.annotations.{ ApiModel, ApiModelProperty } 
import slick.jdbc.GetResult 
import spray.json.DefaultJsonProtocol 

import scala.annotation.meta.field 

case class User(
    id: Int, 
    email: String, 
    name: Option[String] = None, 
    surname: Option[String] = None, 
    passwordId: Option[Int] = None 
) 

object User extends DefaultJsonProtocol{ 
    implicit val getUserResult = GetResult(r => User(r.<<, r.<<, r.<<, r.<<, r.<<)) 

    implicit val userFormat = jsonFormat5(User.apply) 
} 

override def getUser(email: String): Future[Option[(User, UserPassword)]] = db.run { 
    (for { 
     user <- users if user.email === email 
     password <- passwords if password.id === user.id 
    } yield (user, password)).result.headOption 
    } 

User.scala UserPassword.scala

package model 

import com.github.t3hnar.bcrypt.{Password, generateSalt} 
import slick.jdbc.GetResult 


case class UserPassword(id: Int, hashedPassword: Option[String], salt: String = generateSalt) { 
    def passwordMatches(password: String): Boolean = hashedPassword.contains(password.bcrypt(salt)) 
} 

object UserPassword { 

    implicit val getUserPasswordResult = GetResult(r => UserPassword(r.<<, r.<<, r.<<)) 

    def newWithPassword(password: String) = { 
    val salt = generateSalt 
    new UserPassword(0, Some(password.bcrypt(salt)), salt) 
    } 
} 

回答

2

有人可能會這樣嗎?

val futureUserRowAndPwdRow = getUser(email) 
val futureUser: Future[Option[(User, UserPassword)]] = futureUserRowAndPwdRow map { 
    maybeUserRow => maybeUserRow map { 
    case (userRow, pwdRow) => (User(userRow.whatever....), UserPassword(..)) 
    } 
} 
+0

你能解釋一下嗎? –

+0

如果我理解正確,他有一個'Future [Option [(Tables.UsersRow,Tables.PasswordsRow)]]',他想要一個'Future [Option [(User,UserPassword)]]]'。他只需要映射它,以獲得他的案例類'User'和'UserPassword',而不是行類......根本不復雜。 –