光滑3.1 - 将光滑表行对象转换为案例类

时间:2015-12-08 10:31:01

标签: scala slick

我已经使用Slick 3.1代码生成器来创建默认对象和特征Tables.scala

以下方法有效但我想隐式或显式地将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

}

所需方法:

  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

  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)
}

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)
  }
}

1 个答案:

答案 0 :(得分:2)

可能会这样吗?

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