Skip to content

Instantly share code, notes, and snippets.

@ultrox
Last active August 9, 2023 22:29
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 ultrox/46889fe37db624f4d11e2a7e2e8ea390 to your computer and use it in GitHub Desktop.
Save ultrox/46889fe37db624f4d11e2a7e2e8ea390 to your computer and use it in GitHub Desktop.
How expectJson function works in Elm
{-
I got frustrated about how Http.get works, so I expanded all the function in Elm core to get to the bottom of line
-}
expectJson : (Result Error a -> msg) -> Decode.Decoder a -> Expect msg
expectJson toMsg decoder =
let
decodingResult string =
case (Decode.decodeString decoder string) of
Ok v ->
Ok v
Err e ->
Err (Decode.errorToString e)
toResult: r -> Result Http.Error a
toResult response =
case response of
BadUrl_ url -> Err (BadUrl url)
Timeout_ -> Err Timeout
NetworkError_ -> Err NetworkError
BadStatus_ metadata _ -> Err (BadStatus metadata.statusCode)
GoodStatus_ _ body ->
case (decodingResult body) of
Ok v -> Ok v
Err e -> Err (BadBody e)
in
Elm.Kernel.Http.expect "" identity (toResult >> toMsg)
type Msg =
GotPerson Result Http.Error Person
Http.get
{ url = "http://swapi.com/person/1"
, expect = Http.expectJson GotPerson decodePerson
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment