We need to update a counter through our REST API and we're using JSON Patch for our PATCH calls, so it should be something like this:
{"op":"increment", "path":"/counter", "value": 1 }
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, but that could result in problems if more than one client tried to update the counter at the same time.
So how should we tackle this problem and how wrong would it be to add a custom operation like 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 is the correct answer.
that could result in problems if more than one client tried to update the counter at the same time.
Take a careful look at test, which gives you the semantics necessary to describe a precondition. In effect, your document becomes a description of a compare and swap.
how wrong would it be to add a custom operation like increment ?
All the way wrong. RFC 6902 clearly states that the set of operations MUST NOT be extended
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.
You could, of course, define a new specification that includes the operators that you need. But there won't be nearly as much tooling your own vanity patch documents.
In the larger picture, if you are trying to communicate "increment" as opposed to "set", then remote authoring semantics may not be the right choice -- the problem may be trying to tell you that you have the wrong tool in your hand.