Extracting the path to Akka directives

I use akka directives to match a specific path pattern:

/item/quantity 

Examples:

 /apples/100 /bananas/200 

Possible points (for example, "apples", "bananas", ...) are not known in advance, so hard coding of elements using path not an option.

However, I cannot find a PathMatcher that retrieves the path header. I'm looking for something like a form

 val route = get { path(PathHeadAsString) { item : String => path(IntNumber) { qty : Int => complete(s"item: $item quantity: $qty") } ~ complete("no quantity specified") } ~ complete("no item specified") } 

Where

 Get("/apples/100") ~> route ~> check { responseAs[String] shouldEqual "item: apples quantity: 100" } 

Is there a way to extract the first segment of the path?

Matches path(segment) will not match if the number is in the path.

I obviously could use path(segments) to get the List[String] elements of the path, but I would have to manually extract the list and the tail of the list manually, which seems inelegant.

Thank you in advance for your consideration and response.

+5
source share
1 answer

You can compose PathMatchers with modifiers in this way

 path(Segment / IntNumber) { case (item, qty) => complete(s"item: $item quantity: $qty") } 

OR, if you need complete splitting, use pathPrefix :

 val route = pathPrefix(Segment) { item : String => path(IntNumber) { qty : Int => complete(s"item: $item quantity: $qty") } ~ pathEnd { complete("no quantity specified") } ~ complete("something else going on here") } ~ complete("no item specified") 

(Pay attention to the additional directive pathEnd , even with this I would not say that the mapped patterns represent all possible situations.)

From the aka routing directives :

  • pathPrefix directive "Applies this PathMatcher to the prefix of the remaining unsurpassed path after using a leading slash."

  • path directive "Applies this PathMatcher to the remaining unsurpassed path after using a leading slash."

  • pathEnd directive "Only passes the request to its internal route if the request path is fully mapped."

From akka path-matchers , Segment path matcher "Matches if the unsurpassed path starts with a path segment (i.e. no slash). The path segment is retrieved as an instance of String."

+16
source

Source: https://habr.com/ru/post/1240873/


All Articles