带有空正文的 Http DELETE

问题描述 投票:0回答:1

在 Elm (0.18) 中,我正在调用一个 http DELETE 端点,如果成功,则会响应 200 和一个空正文。

在这种情况下(成功)我需要传回一条带有初始 id 的消息(

OnDelete playerId
)。但由于主体是空的,我无法从那里解析它。

目前我正在这样做,但是有没有更优雅的方式来编写

expect
Http.Request
部分:

Http.expectStringResponse (\response -> Ok playerId)

这反映了我当前的代码:

deletePlayer : PlayerId -> Cmd Msg
deletePlayer playerId =
    deleteRequest playerId
        |> Http.send OnDelete


deleteRequest : PlayerId -> Http.Request PlayerId
deleteRequest playerId =
    Http.request
        { body = Http.emptyBody

        , expect = Http.expectStringResponse (\response -> Ok playerId)

        , headers = []
        , method = "DELETE"
        , timeout = Nothing
        , url = "http://someHost/players/" ++ playerId
        , withCredentials = False
        }


type alias PlayerId =
    String
http elm
1个回答
5
投票

附录:Elm v0.19 添加了

expectWhatever
。它的行为与检查错误的
Result
略有不同,但效果类似。


我为“空”200 个回复创建了一个助手

expectUnit

expectUnit : Expect ()
expectUnit =
    Http.expectStringResponse << always <| Ok ()



deleteThing : String -> Request ()
deleteThing path =
    Http.request
        { method = "DELETE"
        , headers = []
        , url = "http://localhost/api"
        , body = Http.jsonBody <| Encode.object [ ( "path", Encode.string path ) ]
        , expect = expectUnit
        , timeout = Nothing
        , withCredentials = False
        }

但对你来说,你能得到的最好的是。

{ # ...
, expect = Http.expectStringResponse << always <| Ok playerId
# , ...
}

或者您可以创建一个助手(实际上是

singleton
pure
代表
Expect

alwaysExpect : a -> Expect a
alwaysExpect =
     Http.expectStringResponse << always << Ok

可以这样使用

{ # ...
, expect = alwaysExpect playerId
# , ...
}

(此内容可在 CC-BY-SA-4.0 下使用,且不得用于闭源 LLM 培训)

© www.soinside.com 2019 - 2024. All rights reserved.