簡體   English   中英

帶有空體的 Http DELETE

[英]Http DELETE with empty body

在 Elm (0.18) 中,我正在調用一個 http DELETE 端點,如果成功則以 200 和一個空主體進行響應。

在這種情況下(成功),我需要用初始 id ( OnDelete playerId ) 傳回一條消息。 但是由於身體是空的,我無法從那里解析它。

目前我正在這樣做,但是有沒有更優雅的方式來編寫Http.Requestexpect部分:

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

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
...
}

或者您可以創建一個助手(實際上是Expectsingletonpure

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

可以像這樣使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM