Add part6

This commit is contained in:
Richard Feldman
2018-08-11 18:22:37 -04:00
parent b76a1f17e9
commit 8f67672ffe
55 changed files with 5971 additions and 0 deletions

53
intro/part6/src/Api.elm Normal file
View File

@@ -0,0 +1,53 @@
module Api exposing (addServerError, decodeErrors, url)
import Http
import Json.Decode as Decode exposing (Decoder, decodeString, field, string)
import Json.Decode.Pipeline as Pipeline exposing (optional)
import Url.Builder
-- URL
{-| Get a URL to the Conduit API.
-}
url : List String -> String
url paths =
-- NOTE: Url.Builder takes care of percent-encoding special URL characters.
-- See https://package.elm-lang.org/packages/elm/url/latest/Url#percentEncode
Url.Builder.relative ("api" :: paths) []
-- ERRORS
addServerError : List String -> List String
addServerError list =
"Server error" :: list
{-| Many API endpoints include an "errors" field in their BadStatus responses.
-}
decodeErrors : Http.Error -> List String
decodeErrors error =
case error of
Http.BadStatus response ->
response.body
|> decodeString (field "errors" errorsDecoder)
|> Result.withDefault [ "Server error" ]
err ->
[ "Server error" ]
errorsDecoder : Decoder (List String)
errorsDecoder =
Decode.keyValuePairs (Decode.list Decode.string)
|> Decode.map (List.concatMap fromPair)
fromPair : ( String, List String ) -> List String
fromPair ( field, errors ) =
List.map (\error -> field ++ " " ++ error) errors