aboutsummaryrefslogtreecommitdiff
path: root/src/client/elm/SimpleHTTP.elm
blob: 99a7056e38189baee1a4e94586e47facefee742b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
module SimpleHTTP
  ( post
  , decodeHttpValue
  ) where

import Http exposing (..)
import Task exposing (..)
import Json.Decode as Json exposing (Decoder)

post : String -> Task Error Value
post url =
  { verb = "POST"
  , headers = []
  , url = url
  , body = empty
  }
    |> Http.send defaultSettings
    |> mapError promoteError
    |> flip Task.andThen handleResponse

handleResponse : Response -> Task Error Value
handleResponse response =
  if 200 <= response.status && response.status < 300
    then Task.succeed response.value
    else fail (BadResponse response.status response.statusText)

promoteError : RawError -> Error
promoteError rawError =
  case rawError of
    RawTimeout -> Timeout
    RawNetworkError -> NetworkError

decodeHttpValue : Decoder a -> Value -> Task Error a
decodeHttpValue decoder value =
  case value of
    Text str ->
      case Json.decodeString decoder str of
        Ok v -> succeed v
        Err msg -> fail (UnexpectedPayload msg)
    _ ->
      fail (UnexpectedPayload "Response body is a blob, expecting a string.")