Last active
April 19, 2018 10:22
-
-
Save k0pernikus/50a49b83653b2093cffdffd3431857cf to your computer and use it in GitHub Desktop.
Transforming a Future of HttpResponse to a Future of a case class using generics through json4s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model._ | |
import akka.stream.Materializer | |
import akka.util.ByteString | |
import org.json4s._ | |
import org.json4s.native.JsonMethods._ | |
import scala.concurrent.duration._ | |
import scala.concurrent.{ExecutionContext, Future} | |
class HttpClient(implicit system: ActorSystem, | |
materializer: Materializer, | |
ec: ExecutionContext) { | |
implicit val formats: Formats = DefaultFormats | |
private def transformResponse[T](r: Future[HttpResponse]) | |
(implicit ev: scala.reflect.Manifest[T]): Future[T] = { | |
r.flatMap { | |
case response@HttpResponse(StatusCodes.OK, _, _, _) => { | |
val buffer = ByteString("") | |
response.entity.dataBytes | |
.runFold(buffer)(_ ++ _) | |
.map(_.utf8String) | |
.map(parse(_).extract[T]) | |
} | |
case _: Any => throw new Throwable("Error!") | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment