Stig Brautaset
Stig Brautaset

Reputation: 2632

spray routing access to url path

I have a route with a portion like this:

...
(pathEnd | path("summary")) {
    parameters(...).as(Query) { query =>
        onSuccess(model ? query) {
            case MyResponse(list) =>
                // at this point I would like to know if I hit pathEnd or
                // path(summary) so I can complete with summary or full response.
                if (???)
                    complete(OK, list)
                else
                    complete(OK, list map (_.toSummary))
        }
    }
}
...

Essentially there's a lot of parameter wrangling and querying of the model that is identical, but I'm doing an extra transformation of the response to shed some data if the summary endpoint is hit. Is it possible to do this in some way?

I tried adding a ctx => after the (pathEnd | path("summary")) { ctx => but that didn't work at all. (The route didn't match, and never returned anything.)

Upvotes: 1

Views: 663

Answers (1)

theon
theon

Reputation: 14380

I gave this custom directive a quick unit test and it seems to work:

  def pathEndOr(p: String) =
    pathEnd.hmap(true :: _) | path(p).hmap(false :: _)

You can use it in you example like so:

...
pathEndOr("summary") { isPathEnd =>
    parameters(...).as(Query) { query =>
        onSuccess(model ? query) {
            case MyResponse(list) =>
                // at this point I would like to know if I hit pathEnd or
                // path(summary) so I can complete with summary or full response.
                if (isPathEnd)
                    complete(OK, list)
                else
                    complete(OK, list map (_.toSummary))
        }
    }
}
...

Upvotes: 1

Related Questions