David Portabella
David Portabella

Reputation: 12720

akka http complete or redirect based on a future

This snipped of akka http server code works:

path("test") {
  if (shouldRedirect())
    redirect(redirectUrl, StatusCodes.PermanentRedirect)
  else
    complete("hello")
}

however, my shouldRedirect() returns a Future[Boolean]. I would need something like this, but returning a Future is not allowed here.

path("test") {
  futureShouldRedirect().map { shouldRedirect =>
    if (shouldRedirect)
      redirect(redirectUrl, StatusCodes.PermanentRedirect)
    else
      complete("hello")
    }
  }
}

How to solve this? ps: I am aware the the complete function accepts a Future inside, however this is not useful in this case I need to either return a complete or a redirect.

Upvotes: 1

Views: 625

Answers (1)

Shankar Shastri
Shankar Shastri

Reputation: 1154

Akka provides predefined directives using you can solve the same.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/

Solution Using onComplete Future Directive:

import akka.http.scaladsl.server.directives._

path("test") {
  onComplete(shouldRedirect()) {
    case Success(true)  => redirect(redirectUrl, StatusCodes.PermanentRedirect)
    case Success(false) => complete("hello")
    case Failure(ex) =>
      complete((InternalServerError, s"An error occurred: ${ex.getMessage}"))
  }
}

The above solution will handle both success and failure cases in case if your shouldRedirect fails.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/future-directives/onComplete.html

Solution Using onSuccess Future Directive:

import akka.http.scaladsl.server.directives._

path("test") {
  onSuccess(shouldRedirect()) { isRedirect =>
    {
      if (isRedirect) redirect(redirectUrl, StatusCodes.PermanentRedirect)
      else complete("hello")
    }
  }
}

The above solution will handle only success scenarios, in case of failure, it will be bubbled up to the exception handler in case if you have defined, else to default exception handler.

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/future-directives/onSuccess.html

Upvotes: 1

Related Questions