akka / akka-http

The Streaming-first HTTP server/module of Akka
https://doc.akka.io/libraries/akka-http/current/
Other
1.34k stars 594 forks source link

no examples of FromRequestUnmarshaller in docs or codebase #1325

Open ktoso opened 7 years ago

ktoso commented 7 years ago

Issue by kornelc Saturday Jul 16, 2016 at 22:56 GMT Originally opened as https://github.com/akka/akka/issues/20972


I'm trying to extract a case class with json4s from the entity (form submission) and realized that there are no examples anywhere on how to create these unmarshallers. The doc just has 'implicit val orderUM: FromRequestUnmarshaller[Order] = ???' as an example which doesn't help much unless somebody is already familiar with unmarshallers, which I am not at this point. It would be great to include a case class unmarshalling example in the docs.

ktoso commented 7 years ago

Comment by levkhomich Sunday Jul 17, 2016 at 04:38 GMT


If request entity is all you need to extract Order, you are probably looking for FromEntityUnmarshaller.

Consider this example:

  def parseWithJson4s[T](jsonStr: String): T = {
    // here goes your json4s logic
    parse(jsonStr).camelizeKeys.extract[T]
  }
  implicit def json4sEntityUnmarshaller[T: Manifest]: FromEntityUnmarshaller[T] = {
    Unmarshaller.stringUnmarshaller.map(parseWithJson4s)
  }

In most cases, boilerplate provided by Unmarshaller object is enough.

If you really need to create unmarshaller from HttpRequest, you can do following:

  case class CustomFromRequestUnmarshaller[T](parse: String => T) extends FromRequestUnmarshaller[T] {
    override def apply(request: HttpRequest)(implicit ec: ExecutionContext, m: Materializer): Future[T] = {
      // here you have access to all parts of request, not just entity
      Unmarshaller.stringUnmarshaller(request.entity).map(parse)
    }
  }
  implicit def json4sRequestUnmarshaller = CustomFromRequestUnmarshaller(parseWithJson4s)
ktoso commented 7 years ago

Comment by kornelc Sunday Jul 17, 2016 at 13:26 GMT


Thanks for the quick response. That worked. I only needed the string as you said.

ktoso commented 7 years ago

Comment by johanandren Monday Jul 18, 2016 at 15:44 GMT


For reference this is the docs for custom unmarshallers: http://doc.akka.io/docs/akka/2.4.8/scala/http/common/unmarshalling.html#custom-unmarshallers

Would be great with a PR with a case class unmarshaller as you say, probably the most common use case when needing a custom unmarshaller.

ktoso commented 7 years ago

Comment by kornelc Monday Jul 18, 2016 at 22:08 GMT


Thanks!

ktoso commented 7 years ago

Comment by kornelc Tuesday Jul 19, 2016 at 12:36 GMT


I reopened this because I think I'm supposed to keep it open based on the last comment. Are we supposed to keep labeled issues open?