Untitled

 avatar
unknown
scala
3 years ago
1.1 kB
4
Indexable
package demo
import zio.{Has, IO, ZIO, ZLayer}

case class User(email: String, name: String)

trait UserRepository {
  def save(user: User): zio.IO[Throwable, Unit]
}

private class UserService(repo: UserRepository) extends User.Service {
  override def save(user: User): IO[Throwable, Unit] =
    repo.save(user)
}

object User {
  type UserEnv = Has[User.Service]
  trait Service {
    def save(user: User): zio.IO[Throwable, Unit]
  }

  val live: ZLayer[Has[UserRepository], Nothing, UserEnv] =
    ZLayer.fromService[UserRepository, User.Service](repo =>
      new UserService(repo)
    )

  def save(user: User): zio.ZIO[UserEnv, Throwable, Unit] =
    zio.ZIO.accessM(hasService => hasService.get.save(user))

  object syntax {
    import scala.language.implicitConversions

    trait UserService {
      def save(): zio.ZIO[UserEnv, Throwable, Unit]
    }

    implicit def userService(user: User): UserService = () => User.save(user)
  }
}

object main {
  import User.syntax._

  val user: User = User("someone@gmail.com", "someone")

  def program(): ZIO[User.UserEnv, Throwable, Unit] =
    user.save()
}
Editor is loading...