Skip to content
This repository has been archived by the owner on Oct 17, 2023. It is now read-only.

Decoding function is not a Bytes.Decoder #9

Open
Gloix opened this issue Mar 2, 2020 · 2 comments
Open

Decoding function is not a Bytes.Decoder #9

Gloix opened this issue Mar 2, 2020 · 2 comments

Comments

@Gloix
Copy link

Gloix commented Mar 2, 2020

Currently the decoder is a simple converter of Bytes to Maybe Image, but elm/http requires a Bytes.Decoder, so the given image loading example does not work.

@miniBill
Copy link

If you need to convert from Bytes -> Maybe Image to Bytes.Decoder Image you can use Bytes.bytes and Bytes.andThen

@Gloix
Copy link
Author

Gloix commented May 25, 2020

The problem is something like in Example#2 in Readme

Http.get
   { url = "/image.png"
   , expect = Http.expectBytes GotImage Image.decode
   }

Http.expectBytes is being passed Image.decode as second param, and that fails (at least in elm/http 2.0.0).

What you're suggesting implies knowing the number of bytes in advance, since Bytes.Decode.bytes needs a number of bytes to decode.

The solution that I found is to use

Http.get
    { url = path
    , expect = Http.expectBytesResponse GotImage httpResponseToImage
    }

httpReponseToImage : Http.Response Bytes -> Result Http.Error (Maybe Image)
httpReponseToImage response =    
    case response of
        Http.GoodStatus_ _ body ->
            Ok <| Image.decode body

        Http.BadUrl_ url ->
            Err (Http.BadUrl url)

        Http.Timeout_ ->
            Err Http.Timeout

        Http.NetworkError_ ->
            Err Http.NetworkError

        Http.BadStatus_ metadata _ ->
            Err (Http.BadStatus metadata.statusCode)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants