Scala未来链接和左/右

时间:2018-03-21 21:02:34

标签: scala playframework silhouette

我在PLAY框架中有这段代码

  def ws: WebSocket = WebSocket.acceptOrResult[JsValue, JsValue] { rh =>
    implicit val req = Request(rh, AnyContentAsEmpty)

    silhouette.SecuredRequestHandler { securedRequest =>
      Future.successful(HandlerResult(Ok, Some(securedRequest.identity)))
    }.map {
      case HandlerResult(_, Some(_)) => wsFutureFlow(rh).map { flow => Right(flow) }
      case HandlerResult(r, None) => Left(r)
    }

    //    wsFutureFlow(rh).map { flow =>
    //      Right(flow)
    //    }.recover {
    //      case e: Exception =>
    //        logger.error("Cannot create websocket", e)
    //        val jsError = Json.obj("error" -> "Cannot create websocket")
    //        val result = InternalServerError(jsError)
    //        Left(result)
    //    }
  }



private def wsFutureFlow(request: RequestHeader): Future[Flow[JsValue, JsValue, NotUsed]] = {
    // Use guice assisted injection to instantiate and configure the child actor.
    implicit val timeout = Timeout(1.second) // the first run in dev can take a while :-(
    val future: Future[Any] = userParentActor ? UserParentActor.Create(request.id.toString)
    val futureFlow: Future[Flow[JsValue, JsValue, NotUsed]] = future.mapTo[Flow[JsValue, JsValue, NotUsed]]
    futureFlow
  }

我是scala的初学者,基本上我要做的是验证对ws端点的请求。如果它已经过身份验证,那么我会给它一个Flow[JsValue, JsValue, None]作为WebSocket连接,否则我需要返回Result。我遇到的问题是我无法弄清楚如何正确设计未来。对于上下文,这是文档https://www.silhouette.rocks/docs/endpoints中的经过身份验证的端点示例。

不编译的行如下:

  case HandlerResult(_, Some(_)) => wsFutureFlow(rh).map { flow => Right(flow) }

我传递给WebSocket.acceptOrResult[JsValue, JsValue]的功能需要返回Future[Either[Result, Flow[In, Out, _]]]。正如您在不编译的行中所看到的那样,我试图Right() Flow,但它并不完全正确。注释部分确实编译。这是编译错误

[error] /home/julian/IdeaProjects/crypto-bloomberg-app/app-admin/src/main/scala/admin/controllers/HomeController.scala:32:62: type mismatch;
[error]  found   : scala.concurrent.Future[scala.util.Right[Nothing,akka.stream.scaladsl.Flow[play.api.libs.json.JsValue,play.api.libs.json.JsValue,akka.NotUsed]]]
[error]  required: Either[play.api.mvc.Result,akka.stream.scaladsl.Flow[play.api.libs.json.JsValue, play.api.libs.json.JsValue, _]]
[error]       case HandlerResult(_, Some(_)) => wsFutureFlow(rh).map { flow => Right(flow) }
[error]                                                              ^
[error] one error found
[error] (app-admin/compile:compileIncremental) Compilation failed
[error] Total time: 4 s, completed 21-Mar-2018 4:29:04 PM

由于

1 个答案:

答案 0 :(得分:2)

使用flatMap代替map

def ws: WebSocket = WebSocket.acceptOrResult[JsValue, JsValue] { rh =>
  implicit val req = Request(rh, AnyContentAsEmpty)

  silhouette.SecuredRequestHandler { securedRequest =>
    Future.successful(HandlerResult(Ok, Some(securedRequest.identity)))
  } flatMap {
    case HandlerResult(_, Some(_)) => wsFutureFlow(rh).map(Right(_))
    case HandlerResult(r, None) => Future.successful(Left(r))
  }
}