Hi guys I'm new in the Scala world and I want to create a simple REST API using Play Framework. I'm working on JSON mappings to Case Classes, and I have maybe a stupid question.
I have a case class that represents a UserDto
(it is used for user registration, and getting some basic info about the user)
case class UserDto(id: Option[Int], email: String, username: String, password: Option[String], confirmedPassword: Option[String])
So as it says in the Play Framework docs, there are multiple ways to map this to JSON, and I'm looking at the automated mapping part
The way I've done it is
val userDtoWrites: OWrites[UserDto] = Json.writes[UserDto]
val userDtoReads: Reads[UserDto] = Json.reads[UserDto]
Now I want to add some validation to my UserDto, for example, to check if the Email is correct.
So my question is, is it somehow possible to create a Read for checking only the email field and add it to the automated generated Read?
I tried it with composeWith, but after running the second Read it only returns the email part.
val checkEmail: String = (JsPath \ "email").read[String](email)
val checkEmailJsString: JsString = checkEmail.map(s => JsString(s))
val newRead = userDtoReads.composeWith(checkEmailJsString))
For example, when a user wants to register:
{"email": "user@email.com", "username": "user","password": "password1234", "confirmedPassword": "password1234"}
That should map to:
UserDto(None, user@email.com, user, password1234, password1234)
if everything is correct. If the password does not match or the email has a bad format is should return 400 for example.