使用RemoteData解码非JSON响应

zou*_*oul 2 http elm

我想使用RemoteData来表示一些不是JSON的数据,我无法弄清楚自定义解码器的位置.我有这些类型:

Http.getString : String -> Request String
RemoteData.sendRequest : Request a -> Cmd (WebData a)
Foo.decode : String -> Result String (List Foo)
Run Code Online (Sandbox Code Playgroud)

现在我想要一条ReceiveFoos (RemoteData String (List Foo))消息来接收已经解码(或失败)的响应.我怎么做?

或者,一般来说,我可以以某种方式提供我自己的String -> Something解码器Http.get,类似于开箱即用支持的JSON解码案例?

Cha*_*ert 6

您可以使用expectStringResponse自定义解码器构建自定义请求.

例如,这里有一个变体Http.get,允许您指定一个接收完整字符串响应体的解码器:

getStringResponse : String -> (Http.Response String -> Result String a) -> Http.Request a
getStringResponse url decoder =
  Http.request
    { method = "GET"
    , headers = []
    , url = url
    , body = Http.emptyBody
    , expect = Http.expectStringResponse decoder
    , timeout = Nothing
    , withCredentials = False
    }
Run Code Online (Sandbox Code Playgroud)

(请注意,这看起来很像JSON版本Http.get实现,)