0
val value = authenticateUser 

private def authenticateUser = {            
   val holder = WS.url(platformUrl + "/userApi/auth/login?username=testuser&password=testPass")
   val res = holder.post(Results.EmptyContent()).onComplete {
     case Success(response) => response.cookies.map{cookie =>   println(cookie.value.get)}
     case Failure(errors) => println("")
       // The `Future` failed.
        }
     }

How to return cookie.value.get from authenticateUser method?

SCouto
  • 7,808
  • 5
  • 32
  • 49
sjain
  • 23,126
  • 28
  • 107
  • 185

1 Answers1

0

First of all, you seem to have many cookies, so it's not clear, the value of which one you want to return.

More importantly, you should not actually return the value itself. The idea is to return the Future, that can be further transformed downstream:

def authenticateUser = WS.url(..)
  .post(Results.EmptyContent)
  .map { _.cookies }
  .map { _.find(_.name == "Auth").flatMap(_.value).getOrElse("") }

Now, somewhere downstream, you can have something like:

 def serve(request: Request): Future[Response] = authenticateUser
    .map { user => 
        serveRequest(user, request)
    }.map { result => makeResponse(result) }

I don't know the specifics of Play, so, consider the Request/Response stuff "pseudocode", but the basic idea is that your entire processing should be a chain of Future transformations. The general rule is to never block the service thread.

Dima
  • 39,570
  • 6
  • 44
  • 70
  • Finally, I got the `Future[String]` from the chain. Now how to get `String` out of `Future[String]` ? – sjain Feb 14 '18 at 15:27
  • As @Dima said, "your entire processing should be a chain of `Future` transformations". That means you hand the `Future` off to the framework and it will use it. That said, if you really need to read the value NOW, for instance while debugging, this should do the trick: `scala.concurrent.Await.result(Future.successful("foo"), scala.concurrent.duration.Duration.Inf)` – László van den Hoek Feb 14 '18 at 15:53
  • @MyGod see `serveRequest(user, request)` in my snippet? The `user` there is the `String` you want. You don't need to get the `String` out of the method, that's wrong. Just get the `Future`, and then `.map` (or `.flatMap`) over it the way I showed, to process further. – Dima Feb 14 '18 at 16:00