Frage

Not sure if this is possible or not but I have a model case class which looks something like below simplified version

case class MyEntity(userName: String, firstName:String,lastName:String)

I have corresponding read and write JSON combinators.

When front end sends requests "userName" is never passed into the incoming JSON but that's a mandatory attribute in saving model to DB. It's server's responsibility to grab "userName" from requestHeader etc. Server has that info. Since userName is not really an optional field (and not client's responsibility to populate it in each JSON request) I am thinking if there is a way to modify incoming JSON before it goes to Read combinator (and gets validated) so model MyEntity is complete and eligible for Read validation.

incoming JSON

{
  "firstName" : "MyFirstName",
  "lastName" : "MyLastName"
}

Want to make it look like following once received from client.

{
   "userName" : "kerberosId",
   "firstName" : "MyFirstName",
   "lastName" : "MyLastName"
}

Probably some kind decorator pattern. is there an elegant way to handle this? I understand model class for JSON requests should only have structure for supporting/validating incoming requests but don't want to have another case class with all info required for db save.

War es hilfreich?

Lösung

Have a look at JSON transformers. You can transform JSON structures using a transformer, like e.g. so:

import play.api.libs.json._

def usernameAppender = __.json.update(
  __.read[JsObject].map { o => o ++ Json.obj("kerberosId" -> kerberosId) }
)

json.transform(usernameAppender)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top