简体   繁体   中英

Scala cats OptionT: Convert Future[Option[A]] to Future[Either[B]]

I am writing a play application in which I have 2 functions as follows

  1. jwtUtils.decodePayload which returns a Try
  2. userRepo.find which returns a Future[Option[User]]

And then my refine fn as shown below

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

}

The refine() fn needs to return a Future[Either]. Is there a better way to write the second half of the refine fn to do that ?

Seems like you can use Either.fromOption from cats library.

currentUser.value.map(opt => 
  Either.fromOption(opt.map(new UserRequest(_, request)), Forbidden)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM