Scala cats OptionT:将Future [Option [A]]转换为Future [Either [B]]

时间:2018-11-05 13:51:07

标签: scala playframework scala-cats

我正在编写一个具有以下2种功能的播放应用程序

  1. jwtUtils.decodePayload返回尝试
  2. userRepo.find,它返回一个Future [Option [User]]

然后按如下所示精炼fn

def refine[A](request: Request[A]) = {

  val jwtToken = request.headers.get("authorization").getOrElse("")

    val currentUser = for {
      json <- OptionT.fromOption[Future]( jwtUtils.decodePayload(jwtToken).toOption )
      user <- OptionT( userRepo.find((json \ "sub").as[String].toLong) )
    } yield user 

    currentUser.value match {
      case fou : Future[Option[User]] => { 
        fou.map { ou =>
          ou match {
            case Some(user) => Right(new UserRequest(user, request)) 
            case _ => Left(Forbidden)
          } 
        }
      }
      case _          => Future.successful( Left(Forbidden) )
    }

}

fine()fn需要返回一个Future [Either]。有没有更好的方法可以写出精炼fn的后半部分来做到这一点?

1 个答案:

答案 0 :(得分:1)

好像您可以在cats库中使用import React, { Component } from "react"; import axios from "axios"; class Lessons extends Component { state = { Questions: [] }; async componentDidMount() { const { data: Questions } = await axios.get( "https://api.myjson.com/bins/1axyok" ); this.setState({ Questions }); console.log(Questions); console.log(this.state.Questions.QuestionID); } render() { return ( <h4 style={{ padding: "20px" }}>{this.state.Questions.QuestionID}</h4> ); } }

Either.fromOption