Home > other >  How to split routes in Akka Http
How to split routes in Akka Http

Time:11-12

What is the best way to split routes that need implicit ActorSystem to different files? Suppose I have this (non-working) code

// in UserRoutes.scala
object UserRoutes {
  val route: Route = ???
}

// in OrderRoutes.scala
object OrderRoutes {
  val route: Route = ???
}

// In MyApp.scala
object MyApp extends App {
  implicit val system = ActorSystem(Behaviors.empty, "my-system")
  implicit val ec = system.executionContext
  
  val route = UserRoutes.route ~ OrderRoutes.route
  
  Http().newServerAt("localhost", 8888).bind(route)
}

All these routes make HTTP requests so they require the presence of ActorSystem, what is the best way to pass it? Make objects into classes and pass it to constructor or is there something more clever?

CodePudding user response:

You can have something like

// in UserRoutes.scala
object UserRoutes {
  def route(implicit sys: ActorSystem): Route = ???
}

// in OrderRoutes.scala
object OrderRoutes {
  def route(implicit sys: ActorSystem): Route = ???
}

In your app, you have the actor system implicitly and then you will be able ton keep val route = UserRoutes.route ~ OrderRoutes.route as it is.

I would usually use a class if I have to use some services

class UserRoutes(auth: AuthService, profile: ProfileService)(implicit sys: ActorSystem) {
    val route : Route = ???
}
  • Related