如何使用 JSON 补丁增加价值?

How to increment value with JSON Patch?

我们需要通过我们的 REST API 更新一个计数器,并且我们正在为我们的 PATCH 调用使用 JSON 补丁,所以它应该是这样的:

{"op":"increment", "path":"/counter", "value": 1 }

问题是JSON补丁不支持这种类型的操作。 ADD 操作只适用于数组,因此最接近的解决方案是使用 REPLACE 操作来替换计数器值,但如果多个客户端同时尝试更新计数器,这可能会导致问题。

那么我们应该如何解决这个问题以及添加自定义操作(如 increment )会有多大错误?

The problem is JSON Patch doesn't support this type of operation. ADD operation is only supposed to work with arrays, so the closest solution would be to use the REPLACE operation to replace the counter value

replace 是正确答案。

that could result in problems if more than one client tried to update the counter at the same time.

仔细查看 test,它为您提供了描述前提条件所需的语义。实际上,您的文档变成了比较和交换的描述。

how wrong would it be to add a custom operation like increment ?

一路走错。 RFC 6902 clearly states that the set of operations MUST NOT 延长

Operation objects MUST have exactly one "op" member, whose value indicates the operation to perform. Its value MUST be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.

当然,您可以定义一个包含所需运算符的新规范。但是你自己的虚荣补丁文件几乎没有那么多工具。

从更大的角度来看,如果您尝试传达“增量”而不是“设置”,那么远程创作语义可能不是正确的选择——问题可能在于试图告诉您您拥有你手里拿错了工具。

尽管标准不支持这一点,但这并没有改变这是一个非常有效的用例的事实。

例证 CosmosDB 添加了对这个要求很高的功能的支持:https://docs.microsoft.com/en-us/azure/cosmos-db/partial-document-update#supported-operations

我不同意接受的、自以为是的答案。标准和规范并非万无一失。

由于规范的限制,我认为你最好的选择是创建一个新的专门的增量操作。