-
Notifications
You must be signed in to change notification settings - Fork 0
Patch Operations
A PatchOperation
represents a single update for a given Entity. A list of PatchOperation
is needed to perform a map, and can be generated one of two ways:
- From an object:
myObject.ToPatchOperations()
- From a list of
JsonPatch
objects:patches.ToPatchOperations<SourceObjectType>()
Both are extension methods in the library, and so to use them you'll need to add using PatchMap;
.
When creating PatchOperation
s from an object, you can control how the operations are generated via these attributes:
-
PatchIgnore
: This property will not generate an operation -
PatchRecursively
: Opposed to a single operation with the value of this property, we'll end up with operations for each field of the property's class.
For example, given the class
public class PatchableItem
{
public int IntValue { get; set; }
[PatchIgnore]
public string ThisShouldNotGenerateAPatch { get; set; }
public List<string> StringList { get; set; } = new List<string>();
[PatchRecursively]
public AddressViewModel Address { get; set; }
}
Running new PatchableItem().ToPatchOperations()
would result in these operations:
[
{ op: 'replace', path: 'IntValue', value: 0 },
{ op: 'replace', path: 'StringList', value: new List<string>() },
{ op: 'replace', path: 'Address/Street1', value: null },
{ op: 'replace', path: 'Address/City', value: null },
{ op: 'replace', path: 'Address/State', value: null }
]
For the JsonPatch
, the reason you specify the source object type in the ToPatchOperations
method is so that it can accurately map the Type's properties and parse the value to the correct type (if possible):
[
{ "op": "replace", "path": "MyIntProperty", "value": "wontparse" },
{ "op": "replace", "path": "MyIntProperty", "value": "10" }
]
The ToPatchOperations
method will throw an exception of JsonPatchParseException
if there was an issue with what the client sent (i.e. the path is invalid). It's recommended you capture these exception at the API level and respond with 400 Bad Request
, including the exception message.
Concepts
PatchMap Library
Examples