0

I'm expecting JsObject in request body and i want to extract and validate required fields

Request Body:

{
    "protoName": "category",
    "clientId": 2
}

My Reads:

  val userReads: Reads[JsObject] = (
    (__ \ "protoName").read[String] ~
    (__ \ "clientId").read[Int] ~
    (__ \ "additionalFields").readNullable[JsObject]
  )((protoName: String, clientId: Int, addfields: Option[JsObject]) => Json.obj(
    "protoName" -> protoName,
    "clientId" -> clientId,
    "additionalFields" -> addfields
  ))

My controller:

  def create = Action.async(parse.json) { r =>

    r.body.transform(ModelGroup.userReads).fold(
      err => Future.successful(BadRequest(JsError.toJson(err))),
      g => ModelGroupsDAO.insert(g).map {
        case true => Ok
        case false => BadGateway
      }
    )

  }

This code works but it's too much boilerplate code... I mean my Reads. I thought this code would work:

  val userReads: Reads[JsObject] = (
    (__ \ "protoName").read[String] ~
    (__ \ "clientId").read[Int] ~
    (__ \ "additionalFields").readNullable[JsObject]
  )(JsObject.apply _)

But it doesn't compile. I think there is a pretty solution like that

Alexander Kondaurov
  • 3,677
  • 5
  • 42
  • 64
  • Why not Forms? https://www.playframework.com/documentation/2.4.x/ScalaForms – Mon Calamari Aug 14 '15 at 07:56
  • In this case i have to write next code: 1. Write Form case class 2. Bind this form 3. Write deserialiaser for that form to JsValue https://www.playframework.com/documentation/2.4.x/ScalaJsonTransformers – Alexander Kondaurov Aug 14 '15 at 08:27

0 Answers0