-
-
Save couellet/3953c050aeb50deceec5f02aaedf4299 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public virtual async Task<T> SaveOrUpdate(T data) | |
{ | |
var document = await GetById(data.Id); | |
if (document == null) | |
{ | |
await Insert(data); | |
} | |
else | |
{ | |
data.ModificationDate = DateTime.UtcNow; | |
var ac = new AccessCondition { Condition = data.ETag, Type = AccessConditionType.IfMatch }; | |
try | |
{ | |
var output = await Client.ReplaceDocumentAsync( | |
UriFactory.CreateDocumentUri(DatabaseId, CollectionId, document.Id), | |
data, new RequestOptions | |
{ | |
AccessCondition = ac | |
}); | |
document.ETag = output.Resource.ETag; | |
data.ETag = output.Resource.ETag; | |
} | |
catch (DocumentClientException ex) | |
{ | |
if (ex.StatusCode == HttpStatusCode.PreconditionFailed) | |
{ | |
throw new OptimisticConcurrencyException( | |
$"Impossible to replace document '{data.Id}' from collection '{CollectionId}'. Precondition failed.", ex); | |
} | |
} | |
} | |
return document; | |
} | |
public async Task<T> SaveOrUpdateOptimistically(string id, Action<T> modifier) | |
{ | |
var doc = await GetById(id); | |
try | |
{ | |
modifier(doc); | |
await SaveOrUpdate(doc); | |
return doc; | |
} | |
catch (OptimisticConcurrencyException) | |
{ | |
return await SaveOrUpdateOptimistically(id, modifier); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment