Play Framework Controller处理多个期货

时间:2017-01-26 14:04:27

标签: scala playframework slick

我有一个Play控制器,它接收来自用户界面的Model对象。此模型对象是我尝试插入数据库的用户。但在我在表中插入此用户之前,我会检查给定的电子邮件地址是否存在已存在的重复用户。如果是,我拒绝请求,如果不是,我插入。我正在使用Slick和Play框架,这是我的控制器代码:

  def registerNewUser(user: User) = {
    dbService.registerNewUser(User.toUserRow(user))
      .map(userID => Ok(Json.obj("status" -> "ok", "userId" -> userID)))
      .recover { case ex => InternalServerError(Json.obj("error" -> s"${ex.getMessage}")) }
  }

  def createUser() = Action.async(parse.tolerantJson) { request =>
    request.body.validate[User].fold(
      errors => Future.successful {
        BadRequest(Json.obj("status" -> "error", "message" -> JsError.toJson(errors)))
      },
      user => {
        val userExists: Future[Boolean] = dbService.userExists(user.email)
        userExists.map(value => {
          if (value) UnprocessableEntity(Json.obj("status" -> "error", "message" -> s"user with email ${user.email.toString} already exists"))
          else registerNewUser(user)
        }).recover {
          case ex => InternalServerError(Json.obj("error" -> s"${ex.getMessage}"))
        }
      } // compilation failure on this line [[ Line X ]]
    )
  }

我认为这种方法没有任何问题,但我的编译器并不满意。它在X线投诉:

Expression of type Future[Object] does not confirm to the expected type _X

这里究竟出现了什么问题?

1 个答案:

答案 0 :(得分:1)

顺便说一下,你不应该使用flatMap代替地图吗?

userExists.map(value => {
          if (value) UnprocessableEntity(Json.obj("status" -> "error", "message" -> s"user with email ${user.email.toString} already exists"))
          else registerNewUser(user)
        })

registerNewUser会返回Future吗?

也许是这样的:

        val userExists: Future[Boolean] = dbService.userExists(user.email)
        userExists.flatMap(value => {
          if (value) Future.successful(UnprocessableEntity(Json.obj("status" -> "error", "message" -> s"user with email ${user.email.toString} already exists")))
          else registerNewUser(user)
        }).recover {
          case ex => InternalServerError(Json.obj("error" -> s"${ex.getMessage}"))
        }