/src/main/scala/net/carjump/WebServer.scala
https://gitlab.com/bomgar/carjump-challenge · Scala · 47 lines · 44 code · 3 blank · 0 comment · 0 complexity · c9dbb00ba2e64038046bf6eeb15c376a MD5 · raw file
- package net.carjump
- import akka.actor.ActorSystem
- import akka.event.Logging
- import akka.http.scaladsl.Http
- import akka.http.scaladsl.Http.ServerBinding
- import akka.http.scaladsl.model._
- import akka.pattern.ask
- import akka.http.scaladsl.server.Directives._
- import akka.http.scaladsl.server.directives.DebuggingDirectives
- import akka.stream.Materializer
- import akka.util.Timeout
- import scala.concurrent.ExecutionContext
- import scala.concurrent.Future
- import scala.concurrent.duration._
- import akka.http.scaladsl.model._
- import akka.http.scaladsl.server._
- import StatusCodes._
- import Directives._
- class WebServer(storingActorRef: StoringActorRef)(implicit mat: Materializer, ec: ExecutionContext, actorSystem: ActorSystem) {
- implicit val timeout = Timeout(5 seconds)
- val route =
- path(LongNumber) { index ⇒
- get {
- val f = (storingActorRef.ref ask StoringActor.Get).mapTo[StoringActor.StoringResult]
- onSuccess(f) { storingResult ⇒
- storingResult match {
- case StoringActor.GetResult(Some(list)) ⇒
- list.get(index) match {
- case Some(element) ⇒
- complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, element))
- case None ⇒
- complete((NotFound, "Element does not exist."))
- }
- case StoringActor.GetResult(None) ⇒
- complete((InternalServerError, "Not yet initialized."))
- }
- }
- }
- }
- def start(interface: String, port: Int): Future[ServerBinding] = {
- val logRoute = DebuggingDirectives.logRequest(("carjump-request", Logging.InfoLevel))(route)
- Http().bindAndHandle(logRoute, interface, port)
- }
- }