Last active
August 9, 2023 22:29
-
-
Save ultrox/46889fe37db624f4d11e2a7e2e8ea390 to your computer and use it in GitHub Desktop.
How expectJson function works in Elm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
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