Question

I want to handle request for creating new entity which is defined as follows:

Group (id, name, avatarLink, groupOwnerId)

groupOwnerId is id of currently logged user.

I have written read object in a following manner

 implicit val groupReads: Reads[models.GroupDAL.Group] = (
 (JsPath \ "name").read[String] and
 (JsPath \ "avatarLink").readNullable[String]
 )(models.GroupDAL.Group.apply(0L,_,_,0L))

What is the correct way to set this variable correctly. Since now I have came up only with one idea - set groupOwnerId value in json on client side, and make custom validator, which validates if given variable is really currently logged user (because it is abnormal to create group whose owner is different user).

But IMO it's kind of rigid solution that I have to do it in this way, and I am wondering If I omitted sth in documentation - maybe there is simpler solution.

Was it helpful?

Solution

I imagine that when you try to deserialize your JSON value, you have the logged in user's ID available somewhere. If so, what about doing something like:

 implicit def groupReads(implicit groupOwnerId: Long): Reads[models.GroupDAL.Group] = (
 (JsPath \ "name").read[String] and
 (JsPath \ "avatarLink").readNullable[String]
 )(models.GroupDAL.Group.apply(0L,_,_,groupOwnerId))

which allows you to write

 val group: Option[Group] = Json.parse(jsonString).asOpt[Group]

as long as the groupOwnerId is available in the implicit scope. However, in this case you probably don't want to use a Long for the groupOwnerId, since this might lead to ambiguous implicit values. A way around this is to wrap it inside a value class, for example:

 class UserId(val underlying: Long) extends AnyVal

and use that type in your definition of the Group type:

 class Group(id: UserId, name: String, avatarLink: Option[String], groupOwnerId: UserId)

Of course then you must change your reader's signature to be:

implicit def groupReads(implicit groupOwnerId: UserId): Reads[models.GroupDAL.Group]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top