Play框架控制器处理多种未来 [英] Play Framework Controller Handling Multiple Futures

查看:85
本文介绍了Play框架控制器处理多种未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Play controller that takes in a Model object that comes in from the user interface. This model object is a User that I'm trying to insert into the database. But before I insert this User in the table, I check if there is a duplicate user that already exist for the given EMail address. If yes, I reject the request and if not I insert. I'm using Slick and Play framework and here is my controller code:

  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线抱怨为:

I do not see anything wrong with this approach, but my compiler is not happy. It complaints at Line X as:

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

这实际上是什么问题?

推荐答案

顺便说一句,您不应该使用flatMap代替此处的地图吗?

Btw shouldn't you use flatMap instead of map here?

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}"))
        }

?

这篇关于Play框架控制器处理多种未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆