Last active
April 25, 2019 13:24
-
-
Save yasuabe/bce840929e77d54b17832c4eafeb8d8e to your computer and use it in GitHub Desktop.
dependency injection sample with ZIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz.zio.{DefaultRuntime, IO, ZIO} | |
// domain layer ----------------------------------------------------------- | |
sealed trait AppError | |
case object NoValue extends AppError | |
case class Movie(id: Int, title: String) | |
trait MovieRepo { | |
def getMovie(id: Int): IO[AppError, Movie] | |
} | |
// application layer ---------------------------------------------- | |
val db = Map[Int, Movie](42 -> Movie(42, "A Movie")) | |
object MovieRepoImpl extends MovieRepo { | |
def getMovie(id: Int): IO[AppError, Movie] = | |
IO.fromEither(db.get(id).toRight(NoValue)) | |
} | |
trait Env { | |
val movieRepo: MovieRepo | |
} | |
object Env extends Env { | |
val movieRepo = MovieRepoImpl | |
} | |
object MovieService { | |
def getMovie(id: Int): ZIO[Env, AppError, Movie] = | |
ZIO.environment[Env] >>= (_.movieRepo.getMovie(id)) | |
} | |
val program: ZIO[Env, AppError, Movie] = MovieService.getMovie(42) | |
// runtime layer ------------------------------------------------- | |
new DefaultRuntime {}.unsafeRunSync(program.provide(Env)) | |
// testing layer ------------------------------------------------- | |
import cats.syntax.either._ | |
new DefaultRuntime {}.unsafeRunSync(program.provide(new Env { | |
val movieRepo = _ => IO.fromEither(NoValue.asLeft) | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment