Skip to content

Instantly share code, notes, and snippets.

@hoangong
Last active January 6, 2019 00:35
Show Gist options
  • Save hoangong/a70e2a5aaf32ed1607db3b29fdcfe5db to your computer and use it in GitHub Desktop.
Save hoangong/a70e2a5aaf32ed1607db3b29fdcfe5db to your computer and use it in GitHub Desktop.
akka http custom serialisation #akka #scala
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller
import akka.stream.Materializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.voi.dto.response.HealthCheck
import com.voi.micro.services.ImplicitPojoMarshaller
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag
trait HealthCheck {
_: ImplicitPojoMarshaller =>
private val mapper = new ObjectMapper()
implicit def genericPojoUnmarshaller[T](implicit c: ClassTag[T]): FromRequestUnmarshaller[T] = {
new FromRequestUnmarshaller[T] {
override def apply(request: HttpRequest)(implicit ec: ExecutionContext, materializer: Materializer): Future[T] =
request.entity.toStrict(5 seconds).map(_.data.decodeString("UTF-8")).map { str =>
mapper.readValue(str, c.runtimeClass).asInstanceOf[T]
}
}
}
lazy val healthCheckApi = path("health-check") {
post {
entity(as[HealthCheck]) { hc =>
complete {
hc
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment