gpt4 book ai didi

REST:当一个请求改变多个实体的状态时返回什么?

转载 作者:行者123 更新时间:2023-12-03 15:41:14 24 4
gpt4 key购买 nike

REST 服务有两个节点
获取 /items返回项目列表:

[
{
"id": 34,
"name": "apple",
"available_amount" : 10
},
{
"id": 37,
"name": "banana",
"available_amount" : 30
},
...
]
发帖 /orders使用请求的项目创建订单(假设我们在这里订购 6 个苹果)并返回订单:
{
"id": 12337,
"items": [
{
"id": 34,
"name": "apple",
"ordered_amount": 6
}
]
}
我如何通知客户端应用程序创建的订单也减少了 available_amount46苹果已经卖掉了。
我是否使用 order 返回受影响的资源?结果,所以客户端知道要更新什么?
像节点路径:
{
"id": 12337,
"items": [
{
"item_id": 34,
"ordered_amount": 6
}
],
"affected_resources" : [
"/items/34"
]
}
甚至完全改变的资源:
{
"id": 12337,
"items": [
{
"item_id": 34,
"ordered_amount": 6
}
],
"affected_resources": {
"items": [
{
"id": 34,
"name": "apple",
"available_amount": 4
}
]
}
}

或者完全不同的东西?
在这些情况下,什么被认为是最佳实践?

最佳答案

您的请求是创建单个新订单资源的 POST。
虽然与客户端相关的是其他资源可能发生的事情,但只有当这些资源在同一个 bounded context 中时才是正确的。 .库存显然是一个不同的有界上下文。
至少只发送当时您认为正确的内容,即新订单的 ID 或新订单的表示。故事可能还有更多……
以每秒 1000 个订单的速度,您可能会发送有关库存的无效数据。
现在,如果通知客户他们的苹果和香蕉订单确实是“苹果和香蕉订单”,那么您可以安全地告诉您的客户;这是一个很好的功能,因为您正在将客户端发送给您的状态传输回客户端,这是事实。您甚至可以告诉客户他们订购了多少。还是实话。说你还剩 N 个苹果和 M 个香蕉……那可能是个谎言。
虽然我们在这里谈论的是资源,但它们与 DDD 中的实体不同。感觉上,有一个足够接近的近似值。资源通常(但不总是)是 DDD 实体(以及扩展聚合)的表示。您的 API 通常会针对单个有界上下文进行操作,因此引入库存等概念显然不在排序有界上下文中。
如果您想让库存成为客户感兴趣的东西,那就是一个单独的 API。
短篇小说

Two customers place orders. Your API dutifully takes their orders.

Customer A is a retail customer and just wants their stuff. You inform them you got their order (A book on REST, and a cloud subscription, right?) and the customer sees that and the order tracking link, and starts requesting order status. "Where's my stuff?"

Customer B is a wholesaler and asks for 1000 of those REST books that it wants to have on hand to fulfill when they resell them. You send them their order, which also contains links to the book inventory. Customer B is glad because those books sell quickly, and needs to ask you (via your separate API of course) whether you have 500 more. Your other API checks inventory and says "I have 500 I can give you right now, but that's only good for the next 15 minutes..."


简而言之,我会说返回任何信息,从表示 POST 成功的最小信息量(一个 ID 和一个 201 响应代码)到最大量(关于客户端发送它时为真的订单的所有内容,加上任何相关的也保证在有界上下文中是真的)。
API 的理想选择是通信 representations of resources客户可以合理地成功采取行动。这包括有关资源的数据和表示客户端可以采取的操作的数据。
虽然这有点超出您的问题, HATEOS在这方面提供了很多指导 ( blog post)。

关于REST:当一个请求改变多个实体的状态时返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66206163/

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