0
votes

I receive error while trying to return action that returns Future of Object as json. My Method looks like that:

  def register: Action[JsValue] = Action.async(parse.json) {
    implicit request: Request[JsValue] => {
      val registerCredentials: RegisterDto = request.body.as[RegisterDto]
      if (registerCredentials.password != registerCredentials.repeatPassword) {
        NotAcceptable("Passwords don't match")
      }
      Try.apply(registerService.createUser(registerCredentials.email, registerCredentials.password))
        .map(user => Ok(Json.toJson(user)))
        .orElse(InternalServerError(s"Error creating new user") )
    }

Register service

registerService.createUser(registerCredentials.email, registerCredentials.password) 

Returns Future of user and I would like to return it from my controller, as database execution is async using Slick.

After trying too start the server I receive following error:

No Json serializer found for type scala.concurrent.Future[login.register.dao.user.User]. Try to implement an implicit Writes or Format for this type.
[error]         .map(user => Ok(Json.toJson(user)))

My User class has a implicit mapper:

case class User(id: Long, email: String, password: String, isActive: Boolean)

object User {
  implicit val personFormat = Json.format[User]
}

I believe there is a problem with returning it as a future and then Json. But It worked for me in another endpoint where I didn't have to use Action.async(parse.json), just Action.async

I am looking for solution to read Json from request and then return some Future of object as json.

1

1 Answers

0
votes

I found solution. I can't map Future to json, but I can map Future so the result is mapped to json. The result should look like:

      Try.apply(registerService.createUser(registerCredentials.email, registerCredentials.password))
        .map(future => future.map(user => Ok(Json.toJson(user))))
        .getOrElse(Future(InternalServerError("Error creating new user")))

I am not sure if it's proper way, if I am wrong please correct me