【发布时间】:2020-08-22 01:05:19
【问题描述】:
我正在尝试使用 doobie、http4s 和猫从数据库中返回用户记录。我一直被类型系统所阻碍,它根据以下代码提供以下错误:
路由器:
val httpRoutes = HttpRoutes.of[IO] {
case GET -> Root / "second" / id =>
val intId : Integer = Integer.parseInt(id)
//if i make thie ConnectionIO[Option[Unit]] it compiles, but returns a cats Free object
val userOption: ConnectionIO[Option[User]] = UserModel.findById(intId, transactor.transactor)
Ok(s"userOption is instance of: ${userOption.getClass} object: ${userOption.toString}")
}.orNotFound
型号:
case class User(
id: Read[Integer],
username: Read[String],
email: Read[String],
passwordHash: Read[String], //PasswordHash[SCrypt],
isActive: Read[Boolean],
dob: Read[Date]
) {
// def verifyPassword(password: String) : VerificationStatus = SCrypt.checkpw[cats.Id](password, passwordHash)
}
object UserModel {
def findById[User: Read](id: Integer, transactor: Transactor[ConnectionIO]): ConnectionIO[Option[User]] = findBy(fr"id = ${id.toString}", transactor)
private def findBy[User: Read](by: Fragment, transactor: Transactor[ConnectionIO]): ConnectionIO[Option[User]] = {
(sql"SELECT id, username, email, password_hash, is_active, dob FROM public.user WHERE " ++ by)
.query[User]
.option
.transact(transactor)
}
}
错误:
Error:(35, 70) Cannot find or construct a Read instance for type:
core.model.User
This can happen for a few reasons, but the most common case is that a data
member somewhere within this type doesn't have a Get instance in scope. Here are
some debugging hints:
- For Option types, ensure that a Read instance is in scope for the non-Option
version.
- For types you expect to map to a single column ensure that a Get instance is
in scope.
- For case classes, HLists, and shapeless records ensure that each element
has a Read instance in scope.
- Lather, rinse, repeat, recursively until you find the problematic bit.
You can check that an instance exists for Read in the REPL or in your code:
scala> Read[Foo]
and similarly with Get:
scala> Get[Foo]
And find the missing instance and construct it as needed. Refer to Chapter 12
of the book of doobie for more information.
val userOption: ConnectionIO[Option[User]] = UserModel.findById(intId, transactor.transactor)
如果我将行更改为 ConnectionIO[Option[User] 到 ConnectionIO[Option[Unit]] 它会编译并运行,但会从我无法计算的猫库中返回一个 Free(...) 对象弄清楚如何解析,我不明白为什么我不能返回我的案例类!
另见 findBy 和 findById 方法的类型声明。在我添加之前,有一个编译错误,说它找到了一个用户,但需要一个读取 [用户]。我尝试将相同的类型声明应用于路由器中 findById 的调用,但它给出了上面提供的相同错误。
提前感谢您的帮助,请耐心等待我的无知。我从来没有遇到过比我更聪明的类型系统!
【问题讨论】:
标签: scala scala-cats cats-effect doobie