mr.nothing
mr.nothing

Reputation: 5399

Scala write collection of objects to HttpResponse

I'm scala beginner and for now I'm trying to build a basic play/slick app (sort of user database).

It seems I've been able to build up all the stuff but data transferring to the front-end.

Here is what I have:

UserDAO.scala

class UserDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends BaseDao {
  import driver.api._

  def entities = TableQuery[UsersTable]

  def all(): Future[Seq[User]] = {
    db.run(entities.result)
  }

  class UsersTable(tag: Tag) extends BaseTable(tag, "USER") {
    def email = column[String]("email")
    def password = column[String]("password")
    def * = (id, email, password) <> (User.tupled, User.unapply)
  }
}

Application.scala

Application @Inject()(userDAO: UserDao) extends Controller {
  def users = Action.async {
    val userList = userDAO.all()
    userList
      .map { list => Ok(list.map(elem => Json.toJson(elem : UserDto))) }
      .recover { case _ => InternalServerError }
  }
}  

UserDTO.scala

case class UserDto(id: Long, login: String)

object UserDto {
  implicit val userWriter = Json.writes[UserDto]

  implicit def from(user: User): UserDto = UserDto(user.id, user.login)
}

What I don't understand is why compiler complains about .map { list => Ok(list.map(elem => Json.toJson(elem : UserDto))) } in Application.scala. It seems that I provided everything required for conversion to json. Could please, anybody, show what I'm doing wrong?

Upvotes: 1

Views: 32

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Replace Ok(list.map(elem => Json.toJson(elem : UserDto))) with Json.toJson(list: Seq[UserDto])

Application @Inject()(userDAO: UserDao) extends Controller {
  def users = Action.async {
    val userList = userDAO.all()
    userList
      .map { list => Ok(Json.toJson(list: Seq[UserDto])) }
      .recover { case _ => InternalServerError }
  }
}  

Upvotes: 2

Related Questions