devoured elysium
devoured elysium

Reputation: 105067

Accessing the segments of a path in akka-http out of a RequestContext?

I'm looking for a way to access, in a method, the list of segments of the path of a request with akka-http:

val route = Seq(
  path("api" / "sub" / IntNumber / IntNumber) { sub }
).reduce(_~_)

def sub(request: RequestContext): Future[RouteResult] = get {
  // how to have access to the two IntNumbers?
}(request)

I know I could just get them straight out in the routing code:

path("api" / "sub" / IntNumber / IntNumber) { (a, b) => sub(a, b) }
...
def sub(a: Int, b: Int)(request: RequestContext): Future[RouteResult] = get {
...

but I would like to keep my routing code clean.

Thanks

Upvotes: 1

Views: 783

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

Let's simplify it visually...

Step 1:

Start with:

path("api" / "sub" / IntNumber / IntNumber) { (a, b) => sub(a, b) }

def sub(a: Int, b: Int)(request: RequestContext): Future[RouteResult] = ???

Don't explicitly pass arguments, Scala will do it for you.

So this:

path("api" / "sub" / IntNumber / IntNumber) { (a, b) => sub(a, b) }

Becomes this:

path("api" / "sub" / IntNumber / IntNumber) { sub }

Step 2:

Since we have this definition:

type Route = RequestContext => Future[RouteResult]

We can replace this part (request: RequestContext): Future[RouteResult] of sub method with Route.

So this:

def sub(a: Int, b: Int)(request: RequestContext): Future[RouteResult] = ???

Becomes this:

def sub(a: Int, b: Int): Route = ???

Or if you prefer this style:

val sub: (Int, Int) => Route = { (a, b) => ??? }

Usage example:

path("api" / "sub" / IntNumber / IntNumber) { sub }

def sub(a: Int, b: Int): Route = complete(s"$a / $b")

val sub: (Int, Int) => Route = { (a, b) => complete(s"$a / $b") }

Note that visually it looks a bit simpler but functionally and in terms of type signatures it's basically the same.

Upvotes: 1

Related Questions