Search code examples
functional-programmingelm

ELM get query parameter as string


Based on this post and thanks to the @glennsl iam getting some where.

First if someone has a link that i could learn about the parses i will be very glad.

page : Url.Url -> String
page url = 
  case (Parser.parse (Parser.query (Query.string "name")) url) of
    Nothing -> "My query string: " ++ (Maybe.withDefault "empty" url.query)
    Just v -> case v of
      Just v2 -> "Finnaly a name"
      Nothing -> "????"

As far i can understand the expression Parser.parse (Parser.query (Query.string "name")) urlis returning a Maybe (Maybe String) I see this as the parser could return something, and if do it could be an string, is that right?

In my mind if i have the parameter name in my url then my first Just would be executed and then i can get the name.

But no mather what i put on my url it always go the the first Nothing

The result i got

enter image description here


Solution

  • The problem is that you're not parsing the path part of the URL, which is what Url.Parser is primarily for. You have to match the path exactly.

    Here's a parser that will match your URL:

    s "src" </> s "Main.elm" <?> (Query.string "name")
    

    Note also that parsing the query string is optional, meaning this will also match your URL:

    s "src" </> s "Main.elm"
    

    But as long as you include a query param parser, that also has to match.

    If all you care about is the query parameter, you'll have to parse the query string specifically, by either writing your own function to do so, or using a library like qs for example:

    QS.parse
        QS.config
        "?a=1&b=x"
    
    == Dict.fromList
        [ ( "a", One <| Number 1 )
        , ( "b", One <| Str "x" ) 
        ]