Advertisement
Cool_Dalek

Modules usage example

Dec 7th, 2022
1,911
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.68 KB | None | 0 0
  1. import cats.effect.*
  2. import cats.effect.std.Dispatcher
  3. import cats.effect.unsafe.Scheduler
  4. import cats.syntax.all.*
  5.  
  6. class BackendModule[F[_]: Async] extends Module.Independent[F, DbConfig, Api[F]]:
  7.  
  8.   def loadConfig: Resource[F, DbConfig] = configAt[DbConfig]("db")
  9.  
  10.   def loadApi(config: DbConfig): Resource[F, Api[F]] =
  11.     DbManager.make[F](config).setupDb.map { xa =>
  12.       Api(DishDao.make[F](xa), MealDao.make[F](xa))
  13.     }
  14.  
  15. end BackendModule
  16.  
  17. class FrontendModule[F[_]: Async] extends Module[F, Unit, F[Unit], Dependencies[F]]:
  18.  
  19.   def loadConfig: Resource[F, Unit] = Resource.unit[F]
  20.  
  21.   def loadApi(config: Unit, dependency: Dependencies[F]): Resource[F, F[Unit]] =
  22.     for {
  23.       dispatcher <- Dispatcher[F]
  24.       given DependencyF[F, DishDao] = dependency._2.map(_.dishes)
  25.       given DependencyF[F, MealDao] = dependency._2.map(_.meals)
  26.       randomizer = Randomizer(dispatcher)
  27.       editor = Editor(dependency._1, dispatcher)
  28.       viewer = DishViewer(dispatcher)
  29.       gui <- AppWindow.show[F](randomizer, editor, viewer)
  30.     } yield gui
  31.  
  32. object FrontendModule:
  33.   type Dependencies[F[_]] = (Scheduler, DependencyF[F, backend.Api])
  34.  
  35. end FrontendModule
  36. type DependencyF[F[_], G[_[_]]] = DeferredSource[F, G[F]]
  37.  
  38. object App extends HardExitResourceApp:
  39.  
  40.   override def run(args: List[String]): Resource[IO, ExitCode] =
  41.     val backend = BackendModule[IO]
  42.     val frontend = FrontendModule[IO]
  43.     for {
  44.       config <- backend.loadConfig
  45.       deferred <- backend.deferredApi
  46.       gui <- frontend.loadModule(runtime.scheduler, deferred)
  47.       _ <- backend.initApi(config, deferred)
  48.       _ <- Resource.eval(gui)
  49.     } yield ExitCode.Success
  50.   end run
  51.  
  52. end App
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement