简体   繁体   中英

Http DELETE with empty body

In Elm (0.18) I'm calling one http DELETE endpoint that if successful responds with 200 and an empty body.

In this case (of success) I need to pass back a message with the initial id ( OnDelete playerId ). But as the body is empty i can't parse it from there.

Currently I'm doing it like this, but is there a more elegant way to write the expect part of Http.Request :

Http.expectStringResponse (\response -> Ok playerId)

?

This reflects my current code:

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 added expectWhatever . It behaves slightly different with the Result being checked for errors, but a similar effect.


I've created a helper expectUnit for "empty" 200 responses.

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
        }

But for you, the best you could get is.

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

Or you could create a helper (which is actually the singleton or pure for Expect )

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

Which could be used like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM