Created
December 7, 2017 20:44
-
-
Save monkeymantra/fe718c305ba49d9b7c41e51d83dca04e to your computer and use it in GitHub Desktop.
Respond to a request with a different status code based on a condition applicable to the future
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def conditionalResponse[T]( | |
successStatusCode: StatusCodes.Success = StatusCodes.OK, | |
errorStatusCode: StatusCodes.ServerError = StatusCodes.InternalServerError, | |
condition: T => Boolean, | |
fut: => Future[T])(implicit m: ToEntityMarshaller[T]): Route = { | |
onSuccess(fut) { | |
case result if condition(result) => complete(successStatusCode -> result) | |
case result => complete(errorStatusCode -> result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Akka-http doesn't make it super-obvious how to generate different response codes for the same marshallable entity, so here's a utility function to let you generate a route. One might make it more general by changing the signature of condition to T => StatusCode.