Bringing it all together

Having the routes implemented, we can now go on with the server definition:

object Server extends App with Routes with JsonSupport {

val config = Config.load()

implicit val system: ActorSystem = ActorSystem("ch14")
implicit val materializer: ActorMaterializer = ActorMaterializer()

DB.initialize(config.database)

lazy val inventory: ActorRef = system.actorOf(InventoryActor.props, InventoryActor.persistenceId)


Http().bindAndHandle(routes, config.server.host, config.server.port)
Await.result(system.whenTerminated, Duration.Inf)
}

We mix together the Routes and JsonSupport traits and define abstract fields. The actor system is needed in order to instantiate the materializer, and a materializer is a machine driving Akka-HTTP. Then we initialize the database, instantiate our persistent actor (which starts to receive events from the journal and restore its state), bind and start the server, and wait for the termination of the actor system.

The way we injected dependencies by defining abstract members and then mixing traits together is called trait-based DI or the thin cake pattern. Usually, in simple cases, we would prefer constructor-based DI, like in the http4s example.

Compared to the http4s implementation, this server is eager. Every statement is executed the moment it is defined (with respect for laziness).

Now we have another version of our store done and can test it as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.200.14