Skip to content

Instantly share code, notes, and snippets.

@couellet
Created February 17, 2017 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save couellet/3953c050aeb50deceec5f02aaedf4299 to your computer and use it in GitHub Desktop.
Save couellet/3953c050aeb50deceec5f02aaedf4299 to your computer and use it in GitHub Desktop.
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