gpt4 book ai didi

REST批量删除多个项目

转载 作者:行者123 更新时间:2023-12-04 19:31:12 27 4
gpt4 key购买 nike

我需要在批处理中按 id 删除多个项目,但是 HTTP DELETE 不支持正文有效负载。

解决选项:

1. @DELETE /path/abc?itemId=1&itemId=2&itemId=3 on the server side it will be parsed as List of ids and DELETE operation will be performed on each item.

2. @POST /path/abc including JSON payload containing all ids. { ids: [1, 2, 3] }

这有多糟糕,哪个选项更可取?有什么选择吗?

更新 : 请注意,性能是这里的关键,它不是对每个单独的 id 执行删除操作的选项。

最佳答案

多年来,许多人对此表示怀疑,正如我们在旁边的相关问题中看到的那样。似乎接受的答案范围从“肯定这样做”到“它明显滥用协议(protocol)”。由于许多问题是多年前提出的,让我们深入研究 2014 年 6 月 (RFC 7231) 以来的 HTTP 1.1 规范,以便更好地了解明显不鼓励或不鼓励的内容。
第一个建议的解决方法:
首先,关于 Section 2 上的资源和 URI 本身:

The target of an HTTP request is called a "resource". HTTP does not limit the nature of a resource; it merely defines an interface that might be used to interact with resources. Each resource is identified by a Uniform Resource Identifier (URI).


基于此,有些人可能会争辩说,由于 HTTP 不限制资源的性质,一个包含多个 id 的 URI将是可能的。我个人认为这是一个解释问题。
关于您提出的第一个解决方法( DELETE '/path/abc?itemId=1&itemId=2&itemId=3' ),我们可以得出结论,如果您将资源视为实体集合中的单个文档,那么这是不鼓励的,而如果您将资源视为实体集合本身,则很好。
第二个建议的解决方法:
关于您提出的第二个解决方法( POST '/path/abc' with body: { ids: [1, 2, 3] } ),使用 POST删除方法可能会产生误导。栏目 Section 4.3.3POST :

The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics. For example, POST is used for the following functions (among others): Providing a block of data, such as the fields entered into an HTML form, to a data-handling process; Posting a message to a bulletin board, newsgroup, mailing list, blog, or similar group of articles; Creating a new resource that has yet to be identified by the origin server; and Appending data to a resource's existing representation(s).


虽然对于 POST 的“等等”功能有一些解释空间,这显然与我们有方法 DELETE 的事实相冲突。用于资源移除,正如我们在 Section 4.1 中所见:

The DELETE method removes all current representations of the target resource.


所以我个人强烈反对使用 POST删除资源。
另一种解决方法:
受您的第二个解决方法的启发,我们建议再做一个:
DELETE '/path/abc' with body: { ids: [1, 2, 3] }
它与解决方法二中的建议几乎相同,但使用正确的 HTTP 方法进行删除。在这里,我们遇到了关于使用实体 body 的困惑。在 DELETE要求。有很多人说它无效,但让我们坚持使用 Section 4.3.5规范:

A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.


因此,我们可以得出结论,规范不会阻止 DELETE从拥有 body有效载荷。不幸的是,一些现有的实现可能会拒绝该请求……但这对我们今天有何影响?
很难 100% 确定,但使用 fetch 提出的现代请求只是不允许 body对于 GETHEAD .这就是 Fetch Standard状态为 Section 5.3关于第 34 条:

If either body exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.


我们可以确认它以与 fetch pollyfill 相同的方式实现。在 line 342 .
最后的想法:
由于 DELETE 的替代解决方法和 body HTTP 规范允许有效负载,并且所有现代浏览器都支持 fetch并且由于带有 polyfill 的 IE10,我推荐这种方式以有效且完整的工作方式进行批量删除。

关于REST批量删除多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55515105/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com