在 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
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 培训)