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.

ProductExportRepository.scala 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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.HttpEntity.Chunked
  6. import akka.http.scaladsl.model._
  7. import akka.stream.scaladsl.{Flow, Source}
  8. import akka.util.ByteString
  9. import com.typesafe.scalalogging.LazyLogging
  10. import de.codingchallenge.csv.CsvOps._
  11. import de.codingchallenge.models.ProductExport
  12. import scala.concurrent.{ExecutionContext, Future}
  13. class ProductExportRepository(actorSystem: ActorSystem)(implicit ec: ExecutionContext) extends LazyLogging {
  14. private implicit val as: ActorSystem = actorSystem
  15. val headerLine = "produktId|name|beschreibung|preis|summeBestand"
  16. val baseUrl = "http://localhost:8080"
  17. def add(p: Source[ProductExport, NotUsed], articlesSize: Int): Future[HttpResponse] = {
  18. val sourceWithHeader = p.via(csvFlow)
  19. .prepend(Source.single(headerLine))
  20. .intersperse("\n")
  21. .map(ByteString.apply)
  22. // it did not work with charset information
  23. val entity = Chunked.fromData(
  24. ContentType.WithMissingCharset(MediaTypes.`text/csv`),
  25. sourceWithHeader
  26. )
  27. Http()
  28. .singleRequest(
  29. HttpRequest(
  30. method = HttpMethods.PUT,
  31. uri = s"$baseUrl/products/$articlesSize",
  32. entity = entity))
  33. .map{res =>
  34. logger.info(s"Server responded with $res")
  35. res
  36. }
  37. }
  38. private val csvFlow: Flow[ProductExport, String, NotUsed] =
  39. Flow.fromFunction{p =>
  40. logger.info(s"processing export record $p")
  41. p.toCsvLine
  42. }
  43. }