Skip to content

Instantly share code, notes, and snippets.

@mossprescott
Last active May 29, 2023 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mossprescott/70ad600f3a69935d30fe093fd034da54 to your computer and use it in GitHub Desktop.
Save mossprescott/70ad600f3a69935d30fe093fd034da54 to your computer and use it in GitHub Desktop.
Parse a single query param
import Url
import Url.Parser
import URL.Parser.Query
parseQuizNumber : String -> Maybe Int
parseQuizNumber urlString =
let
dropPath : Url -> Url
dropPath url =
{ url | path = "" }
parseUrl : Url -> Maybe (Maybe Int)
parseUrl = Url.Parser.parse (Url.Parser.query (Url.Parser.Query.int "quiz"))
in
case Url.fromString urlStr |> Maybe.andThen (dropPath >> parseUrl) of
Just (Just qid) ->
-- The URL was valid, the parameter was present and contained an int:
Just qid
Just Nothing ->
-- The URL was valid, we parsed it, but there was no "quiz" param, or it wasn't an int
Nothing
Nothing ->
-- The URL was invalid
Nothing
@mossprescott
Copy link
Author

I tried pretty hard to verify that this will compile and do something sensible, but there could be a problem with those imports or something.

cc @TundraGreen

@mossprescott
Copy link
Author

mossprescott commented May 29, 2023

The next step to use is to modify your main so it looks something like this:

main : Program String Model Msg
main =
    Browser.document
        { init = \urlString -> ( init (parseQuizNumber urlString), Cmd.none )
        , subscriptions = subscriptions
        , update = update
        , view = view
        }

And, in index.html:

      var app = Elm.Main.init({
        node: document.querySelector('main'),
        flags: window.location.href
      });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment