Evancz / url-parser and multiple request parameters
I'm not sure how to access multiple query parameters.
There is no example in the source code here .
I know how to get a single query parameter using <?>
:
routeParser : Url.Parser (Route -> a) a routeParser = Url.oneOf [ Url.map HomeRoute Url.top , Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy") ] parseLocation : Location -> Route parseLocation location = location |> Url.parsePath routeParser |> Maybe.withDefault NotFoundRoute
With parsePath
I can get Dict
with query parameters, but is there an elegant way using <?>
?
Edit:
I used this example in elm-repl
:
> parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "") -- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm The 1st argument to function `parsePath` is causing a mismatch. 5| parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Function `parsePath` is expecting the 1st argument to be: Parser (Maybe String -> Maybe String) (Maybe String) But it is: Parser (Maybe String -> Maybe String -> Maybe String) (Maybe String) Hint: It looks like a function needs 1 more argument.
source to share
You can chain <?>
together for multiple query parameters. Let's say yours was SettingsRoute
also expecting an pageNumber
integer argument:
type Route = ... | SettingsRoute (Maybe String) (Maybe Int)
Then your parser might look like this:
Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy" <?> Url.intParam "pageNumber")
Request parameters from the incoming URL do not have to be in the same order as the map operator. The following example will give the same results for the above route:
settings?sortBy=name&pageNumber=3 settings?pageNumber=3&sortBy=name
Edit
You've added an example from the REPL. The problem you are having in the REPL is that you are not matching correctly what takes two parameters. Consider this example for the REPL:
> type alias SearchParams = { search : Maybe String, sortBy : Maybe String } > parsePath (map SearchParams (s "blog" <?> stringParam "search" <?> stringParam "sortBy")) (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "") Just { search = Just "cats", sortBy = Just "name" } : Maybe.Maybe Repl.SearchParams
source to share