Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active July 7, 2021 13:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choonkeat/14c0ecc8f6ba929a76ee03647cb96ded to your computer and use it in GitHub Desktop.
Save choonkeat/14c0ecc8f6ba929a76ee03647cb96ded to your computer and use it in GitHub Desktop.
Http.task { resolver = Http.stringResolver decoder, ... }
module Http.Extra exposing (..)
import Http
import Json.Decode
{-| to obtain a String from `Http.task`
Http.task
{ resolver = Http.stringResolver httpStringBodyResolver
, ...
}
-}
httpStringBodyResolver : Http.Response String -> Result Http.Error String
httpStringBodyResolver resp =
case resp of
Http.GoodStatus_ m s ->
Ok s
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
Err (Http.BadStatus m.statusCode)
{-| applies a json decoder to response of `Http.task`
Http.task
{ resolver = Http.stringResolver (httpJsonBodyResolver thingDecoder)
, ...
}
-}
httpJsonBodyResolver : Json.Decode.Decoder a -> Http.Response String -> Result Http.Error a
httpJsonBodyResolver decoder resp =
case resp of
Http.GoodStatus_ m s ->
Json.Decode.decodeString decoder s
|> Result.mapError (Json.Decode.errorToString >> Http.BadBody)
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
Json.Decode.decodeString decoder s
-- just trying; if our decoder understands the response body, great
|> Result.mapError (\_ -> Http.BadStatus m.statusCode)
{-| httpRawResolver makes no judgement of what is good or bad http status.
if the http request was executed, we'll get the response metadata and data
-}
httpRawResolver : Http.Response String -> Result Http.Error { metadata : Http.Metadata, data : String }
httpRawResolver resp =
case resp of
Http.GoodStatus_ m s ->
Ok { metadata = m, data = s }
Http.BadStatus_ m s ->
Ok { metadata = m, data = s }
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment