Skip to content

Instantly share code, notes, and snippets.

@adamw
Last active June 4, 2020 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamw/696e2c928399e67be19f459e05f2a2d6 to your computer and use it in GitHub Desktop.
Save adamw/696e2c928399e67be19f459e05f2a2d6 to your computer and use it in GitHub Desktop.
// UserModel.scala
import zio.{Task, ZIO, ZLayer}
object DB {
// 1. service
trait Service {
def execute(sql: String): Task[Unit]
}
// 2., 3. omitted here
}
object UserModel {
// 1. service
trait Service {
def insert(u: User): Task[Unit]
}
// 2. layer - service implementation
val live: ZLayer[DB, Nothing, UserModel] = ZLayer.fromService { db =>
new Service {
override def insert(u: User): Task[Unit] =
db.execute(s"INSERT INTO user VALUES ('${u.name}')")
}
}
// 3. accessor
def insert(u: User): ZIO[UserModel, Throwable, Unit] = ZIO.accessM(_.get.insert(u))
}
// ---
// 4. type aliases in package.scala
type DB = Has[DB.Service]
type UserModel = Has[UserModel.Service]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment