url
url copied to clipboard
Allow ignoring the path / Just parsing query parameters
We're running an Elm app as an embedded element, so we don't actually control the url where the elm app runs. We are interested in variables stored in query parameters though, and as far as I know there's no way to construct a parser which allows us to just parse queries.
Our current workaround is to alter the Url object and always set path to "/", but this feels a bit hackish.
This ignores the Url.path: Url.Parser.parse (Url.Parser.query queryParser) url
EDIT: @marmutro unfortunately this does not work in every case. See these examples:
import Url
import Url.Parser as Parser
import Url.Parser.Query as Query
queryParser =
Query.int "CompID"
works =
"http://www.google.com?CompID=123"
|> Url.fromString
|> Maybe.andThen (Parser.parse (Parser.query queryParser)) -- Just (Just 123)
doesNotWork =
"http://www.google.com/test?CompID=123"
|> Url.fromString
|> Maybe.andThen (Parser.parse (Parser.query queryParser)) -- Nothing
Looks like I'm going to need to manually parse url.query myself.
I believe I ran into the same problem. I fixed this using a "trick" I saw on the official forum which is to first set the path to empty:
extractSearchArgument : String -> Url -> Maybe String
extractSearchArgument key location =
{ location | path = "" }
|> Url.Parser.parse (Url.Parser.query (Url.Parser.Query.string key))
|> Maybe.withDefault Nothing
Oh yeah, I do the same thing:
-- so that parsers run regardless of path:
normalizedUrl =
{ url | path = "" }
Would be nice to have either Url.Parser.query do this or have another function to do so available.
I'd be happy to contribute it, if it's wanted.
Is it going to be fixed? This is the second time i face this issue having literally no idea what is going wrong, thats kinda sad
no anytime soon probably, use different package
I'd like to report that I just ran into this in the wild, and it was very confusing and frustrating.
To offer a concrete example I was repl-testing with, in case it helps future searchers:
import Url
import Url.Parser
import Url.Parser.Query
"https://hostname.tld:1234/path1/path2?foo=alpha&bar=beta" |>
Url.fromString |>
Maybe.andThen (\urldata ->
{urldata| path = ""} |> -- OMG why is this secret sauce necessary?
Url.Parser.parse (Url.Parser.query (Url.Parser.Query.string "foo"))
)