You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ArticleRepository.scala 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package de.codingchallenge.repositories
  2. import akka.NotUsed
  3. import akka.actor.ActorSystem
  4. import akka.http.scaladsl.Http
  5. import akka.http.scaladsl.model.{HttpRequest, Uri}
  6. import akka.stream.scaladsl.{Flow, Framing, Source}
  7. import akka.util.ByteString
  8. import com.typesafe.scalalogging.LazyLogging
  9. import de.codingchallenge.csv.CsvOps._
  10. import de.codingchallenge.models.Article
  11. class ArticleRepository(actorSystem: ActorSystem) extends LazyLogging{
  12. private implicit val as = actorSystem
  13. // might be a good idea to make that value configurable
  14. val baseUrl: String = "http://localhost:8080"
  15. def getArticles(limit: Int): Source[Article, NotUsed] = Source.fromFuture(
  16. Http()
  17. .singleRequest(HttpRequest(uri = s"$baseUrl/articles/$limit"))
  18. ).flatMapConcat(res =>
  19. res.entity
  20. .dataBytes
  21. .via(lineDelimiter)
  22. .via(articleFlow))
  23. val lineDelimiter: Flow[ByteString, ByteString, NotUsed] =
  24. Framing.delimiter(ByteString("\n"), 128, allowTruncation = true)
  25. val articleFlow: Flow[ByteString, Article, NotUsed] = Flow[ByteString]
  26. .map(_.utf8String)
  27. .drop(1)
  28. .map{e => logger.info(s"Parsing CSV string: $e"); e}
  29. .map(_.csvToOptOf[Article])
  30. .map{
  31. case Some(a) => a
  32. case _ => throw new IllegalStateException("Malformed CSV data aborting stream")
  33. }
  34. }