Created
August 9, 2024 22:50
-
-
Save DGolubets/aa8519781e20302cb1d7254686aa5bbf to your computer and use it in GitHub Desktop.
Scala DI wth implicits and Cats
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
//> using toolkit typelevel:default | |
import cats.effect.* | |
object Hello extends IOApp.Simple: | |
def run = | |
val server = for { | |
given Database <- Postgres.build | |
given UserRepo <- DefaultUserRepo.build | |
given UserService <- DefaultUserService.build | |
given UserController <- DefaultUserController.build | |
httpServer <- HttpServer.build | |
} yield httpServer | |
server.use(_.run) | |
// DB | |
trait Database | |
object Postgres: | |
def build: Resource[IO, Postgres] = ??? | |
class Postgres extends Database {} | |
// Repo | |
trait UserRepo | |
object DefaultUserRepo: | |
def build(using db: Database): Resource[IO, DefaultUserRepo] = | |
Resource.pure(DefaultUserRepo(db)) | |
class DefaultUserRepo(db: Database) extends UserRepo {} | |
// Service | |
trait UserService | |
object DefaultUserService: | |
def build(using repo: UserRepo): Resource[IO, DefaultUserService] = | |
Resource.pure(DefaultUserService(repo)) | |
class DefaultUserService(repo: UserRepo) extends UserService {} | |
// Controller | |
trait UserController | |
object DefaultUserController: | |
def build(using service: UserService): Resource[IO, DefaultUserController] = | |
Resource.pure(DefaultUserController(service)) | |
class DefaultUserController(service: UserService) extends UserController {} | |
// Http Server | |
object HttpServer: | |
def build(using controller: UserController): Resource[IO, HttpServer] = | |
Resource.pure(HttpServer(controller)) | |
class HttpServer(controller: UserController): | |
def run: IO[Unit] = ??? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment