从Scala Future映射数据

时间:2017-08-14 15:05:56

标签: scala playframework playframework-2.0 future

我正在实施一项任务来调用Play框架中的某些Rest端点,这里是我服务中的代码:

override def getAccessToken(loginData: LoginData): Future[Unit] = {
    logger.info("get access token from HAT")
    val accessTokenURL = // This is the URL to be called
    logger.info(accessTokenURL)
    ws
      .url(accessTokenURL)
      .withHttpHeaders(
        HeaderNames.ACCEPT -> ContentTypes.JSON,
        "username" -> loginData.username,
        "password" -> loginData.password
      )
      .withRequestTimeout(timeout)
      .get()
      .map {
        response => response.status match {
          case Status.OK =>
            val responseAsJson = response.json
            Future.successful((responseAsJson \ "accessToken").as[String])

          case _ =>
            val message = (response.json \"message").asOpt[String]
            throw new GeneralBadRequestException(message.get)
        }

      }
  }

val accessTokenURL的回复类似于:

{
    "accessToken": "some token",
    "userId": "some user id"
}

然后在我的控制器中,我编写了一些这样的函数来从上面的服务中获取数据:

  private def handleAccessToken: LoginData => Future[Result] = { loginData =>

    requestHATService.getAccessToken(loginData).map (
      response => Ok(response)) recover {
      case e =>
        val errorJson: JsValue = Json.obj(
          "status" -> "ERROR",
          "error" -> Json.obj(
            "code" -> "ERROR",
            "message" -> e.getMessage
          )
        )
        BadRequest(errorJson)
    }
  }

我此刻苦苦挣扎的是函数response => Ok(response))中的handleAccessToken部分,我想将它包含在Ok Result中以返回控制器响应但我无法得到数据输出,特别是accessToken,当我试图编译代码时,这样的错误抛出:

  

无法将单元实例写入HTTP响应。尝试定义一个   可写[单位]

编辑:感谢@Frederic的回答,我在这里有另一个问题,如何将响应字符串附加到某些JsValue并传递给Ok Result,有些像

  val successJson: JsValue = Json.obj("status" -> "OK")
    requestHATService.getAccessToken(loginData).map (
      response => 
            // code to attach response to successJson here 
            Ok(successJson)) recover {
                 ......
            }

1 个答案:

答案 0 :(得分:1)

问题在于: def getAccessToken(loginData: LoginData): Future[Unit]

它应该是: def getAccessToken(loginData: LoginData): Future[String]

您需要更多解释吗?