D_K
D_K

Reputation: 65

Play (Scala) handling different Content-Type within the same action

I am developing a web service which accepts JSON data. Sometimes input data comes with attachments like image or some PDF file. In that case this data comes as multi-part data.

I need to create action which accepts both content type. And depending on content type it should be able to parse the json and retrieve the attachment related metadata from json and then download the attachment.

I have two actions which handles things separately

    def multiPartAction: Action[MultipartFormData[Array[Byte]]] = Action(multipartFormDataAsBytes)={request =>
...
}

Second action

 def handleJSon: Action[JsValue] = Action.async(parse.json) {
    request =>
...
}

How do I handle these two actions together in one action?

Upvotes: 3

Views: 682

Answers (1)

Artur Nowak
Artur Nowak

Reputation: 5354

You can either specify your own body parser that is a combination of two, similarly to how it is done here, or leave the body parser out, sticking to default AnyContent body type. Then:

def action = Action { request =>
  val body: AnyContent = request.body
  val jsonBody: Option[JsValue] = body.asJson
  val multipartBody: Option[MultipartFormData[TemporaryFile] =
    body.asMultipartFormData

  (jsonBody map getResponseForJson) orElse
    (multipartBody map getResponseForAttachment) getOrElse
    BadRequest("Unsupported request body")
}

Upvotes: 1

Related Questions