Chain multiple HTTP calls from submodule

This post is in response to my previously posted question (which is now closed):

The solution to this post is great and taught me a deeper understanding of how commands work. I ran into an issue when I needed to chain multiple HTTP calls (login and then getUser with the token from login) and I did not see how to do that with the constructor pattern. I found the following article helpful:

I ended up with the following:

login : Config -> String -> String -> (Task Error User) 
login config email password =
    maybeLogin config email password 
        |> Task.mapError HttpError 
        |> Task.andThen
            (\token -> createUser token config 
                            |> Task.mapError HttpError

maybeLogin: Config -> String -> String -> (Task Http.Error Token) 
maybeLogin config email password =
        url             = config.apiUrl ++  "/token"
        body            = "grant_type=password" ++
                          "&username=" ++ percentEncode email ++
                          "&password=" ++ percentEncode password
        rememberHeaders = getRememberHeaders config.setCookie 
    Http.task { url     = url 
              , method  = "POST"
              , body    = Http.stringBody "application/x-www-form-urlencoded" body
              , headers = config.defaultHeaders ++ rememberHeaders
              , resolver= (Http.stringResolver <| handleJsonResponse <| tokenDecoder)
              , timeout = Nothing
1 Like


Some tips:

  • you can use this module to build up urls, instead of string concatenation. Then you won’t need to percent encode things yourself and rely on some Battle-Tester code instead :slight_smile:
  • Almost everyone in the elm community uses the elm-format code formatter. It is very opinionated (it will change your formatting style, too, unfortunately), but it ensures the same formatting style across the community, which is great!

Awesome. Thanks @Philipp_Krueger!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.