-
Hi there - huge newbie warning. What do people generally return from the traits that represent the data access layer? Returning Having the trait return something like What's the idioms/styles/best practice here? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @yatesco One option is to return Another option (the one I prefer) is to have the data access trait be parameterized with The functions returning // UserAlgebra.scala
trait UserAlgebra[F[_]] {
def getUser(userId: Long): F[User]
def getUserIfExists(userId: Long): F[Option[User]]
}
// UserRepo.scala
object UserRepo extends UserAlgebra[ConnectionIO] {
def getUser(userId: Long): ConnectionIO[User] =
selectUserById(userId).unique
def getUserIfExists(userId: Long): ConnectionIO[Option[User]] =
selectUserById(userId).option
def selectUserById(id: Long): Query0[User] =
sql"SELECT * FROM users WHERE id = $id".query
} Notice how the query returned from
I hope this helps :) |
Beta Was this translation helpful? Give feedback.
Hey @yatesco
One option is to return
ConnectionIO
from the functions in the database access trait, sinceConnectionIO
s can be combined into oneConnectionIO
(using.flatMap
or afor
comprehension) that runs multiple operations on the database on the same connection (or even the same transaction). After combining yourConnectionIO
s, it's easy to later turn them into anIO
using.transact
.Another option (the one I prefer) is to have the data access trait be parameterized with
F[_]
, and returnF
s from all functions. ThisF
could later, for example, be fixed toConnectionIO
in an implementation of the trait.The functions returning
Query
orUpdate
could be kept in an object or a package sepa…