Different routes based on request content type Spray Routing 1.2.1
Asked Answered
D

1

7

I would like to support a couple of different content types submitted to the same URL:

e.g:

application/x-www-form-urlencoded, multipart/form-data, application/json

I would like to do something like:

post {
  contentType(`application/x-www-form-urlencoded`) | 
  contentType(`multipart/form-data`) {
     // user POSTed a form
     entity(as[MyCaseClass]) { data =>
        complete { data.result }
     }
  } ~ contentType(`application/json`) {
     // user POSTed a JSON object
     entity(as[MyCaseClass]) { data =>
        complete { data.result }
     }
  }
}

I think there may be some way to do this with custom marshaling and unmarshaling, but I only need it in one or two spots in my service and this seems pretty simple. Can someone help?

Deltoro answered 3/4, 2014 at 1:43 Comment(0)
D
6

There is a really elegant way to achieve this thanks to deep cleverness in the Spray marshalling system. The code (gist) illustrates this:

case class User(name: String, no: Int)

// Json marshaller
object UnMarshalling extends DefaultJsonProtocol {
  val jsonUser = jsonFormat2(User)
  val textUser = Unmarshaller[User](`text/plain`) {
      case HttpEntity.NonEmpty(contentType, data) =>
        val res = data.asString.drop(5).dropRight(1).split(',')
        User(res(0),res(1).toInt)
  }
  implicit val userMarshal = Unmarshaller.oneOf(jsonUser, textUser)
}

class UnMarshalTest extends FunSpec with ScalatestRouteTest with Matchers {
  import UnMarshalling._

  // Marshals response according to the Accept header media type
  val putOrder = path("user") {
    put {
      // Namespace clash with ScalaTestRoutes.entity
      MarshallingDirectives.entity(as[User]) {
        user =>
          complete(s"no=${user.no}")
      }
    }
  }

  describe("Our route should") {

    val json = """ {"name" : "bender", "no" : 1234} """

    it("submit a json") {
      Put("/user", HttpEntity(`application/json`,json)) ~> putOrder ~> check {
        responseAs[String] should equal("no=1234")
      }
    }
    it("Submit text") {
      Put("/user", HttpEntity(`text/plain`,"""User(Zoidberg,322)""")) ~> putOrder ~> check {
        responseAs[String] should equal("no=322")
      }
    }
  }
}
Dorsett answered 3/4, 2014 at 7:29 Comment(4)
Wow, that is a an incredibly informative answer - but I'm looking for two ways to unmarshal the incoming POSTed data based on the content type of the request. I will always output application/json no matter what format the request came in.Deltoro
The unmarshaller works in a very similar way (implicits again) so you would just have to explicitly provide the unmarshal in the same way that I provided a marshaller. I'll take a peek at it in the next 24 hoursDorsett
@SaminOakland Hope this hits a little closer to what you are after :)Dorsett
It took me hour to find the answer, and only yours finally helped me, thanks!Depew

© 2022 - 2024 — McMap. All rights reserved.