Mohith Thimmaiah
Mohith Thimmaiah

Reputation: 93

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 ?

Upvotes: 3

Views: 850

Answers (1)

Yevhenii Popadiuk
Yevhenii Popadiuk

Reputation: 1054

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

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

Upvotes: 2

Related Questions