Skip to content

Instantly share code, notes, and snippets.

@keisisqrl
Created September 27, 2019 20:35
Show Gist options
  • Save keisisqrl/df041bf1f61c7ca1a88683e2a4ea6280 to your computer and use it in GitHub Desktop.
Save keisisqrl/df041bf1f61c7ca1a88683e2a4ea6280 to your computer and use it in GitHub Desktop.
Utility functions to decode Http binary file response to data URI in elm
import Base64 exposing (fromBytes)
import Bytes exposing (Bytes)
import Dict
import Http exposing (Response(..))
import Result exposing (fromMaybe)
dataReadyResponse : Bytes -> Result Http.Error String
dataReadyResponse =
fromBytes
>> fromMaybe (Http.BadBody "Couldn't Base64 encode response")
processFileResponse : Http.Response Bytes -> Result Http.Error String
processFileResponse resp =
case resp of
Timeout_ ->
Err Http.Timeout
NetworkError_ ->
Err Http.NetworkError
BadUrl_ str ->
Err (Http.BadUrl str)
BadStatus_ { statusCode } _ ->
Err (Http.BadStatus statusCode)
GoodStatus_ meta body ->
goodResponse meta body
goodResponse : Http.Metadata -> Bytes -> Result Http.Error String
goodResponse { headers } body =
let
mediaType =
Dict.get "content-type" headers
|> Maybe.withDefault ""
dataStart =
"data:"
++ mediaType
++ ";base64,"
in
dataReadyResponse body
|> Result.map
(\b64 -> dataStart ++ b64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment