/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

  1. package net.carjump
  2. import akka.actor.ActorSystem
  3. import akka.event.Logging
  4. import akka.http.scaladsl.Http
  5. import akka.http.scaladsl.Http.ServerBinding
  6. import akka.http.scaladsl.model._
  7. import akka.pattern.ask
  8. import akka.http.scaladsl.server.Directives._
  9. import akka.http.scaladsl.server.directives.DebuggingDirectives
  10. import akka.stream.Materializer
  11. import akka.util.Timeout
  12. import scala.concurrent.ExecutionContext
  13. import scala.concurrent.Future
  14. import scala.concurrent.duration._
  15. import akka.http.scaladsl.model._
  16. import akka.http.scaladsl.server._
  17. import StatusCodes._
  18. import Directives._
  19. class WebServer(storingActorRef: StoringActorRef)(implicit mat: Materializer, ec: ExecutionContext, actorSystem: ActorSystem) {
  20. implicit val timeout = Timeout(5 seconds)
  21. val route =
  22. path(LongNumber) { index
  23. get {
  24. val f = (storingActorRef.ref ask StoringActor.Get).mapTo[StoringActor.StoringResult]
  25. onSuccess(f) { storingResult
  26. storingResult match {
  27. case StoringActor.GetResult(Some(list))
  28. list.get(index) match {
  29. case Some(element)
  30. complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, element))
  31. case None
  32. complete((NotFound, "Element does not exist."))
  33. }
  34. case StoringActor.GetResult(None)
  35. complete((InternalServerError, "Not yet initialized."))
  36. }
  37. }
  38. }
  39. }
  40. def start(interface: String, port: Int): Future[ServerBinding] = {
  41. val logRoute = DebuggingDirectives.logRequest(("carjump-request", Logging.InfoLevel))(route)
  42. Http().bindAndHandle(logRoute, interface, port)
  43. }
  44. }