Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created February 23, 2017 01:41
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 dcomartin/2a0e0378d847360001442c20c12c6dbc to your computer and use it in GitHub Desktop.
Save dcomartin/2a0e0378d847360001442c20c12c6dbc to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Caching.Memory;
namespace Demo
{
public static class DocumentDbCacheClient
{
private static readonly IMemoryCache Cache;
static DocumentDbCacheClient()
{
Cache = new MemoryCache(new MemoryCacheOptions());
}
public static async Task<Document> GetDocumentById(this DocumentClient client, string collectionLink, string id)
{
Document cacheEntry;
var cacheKey = $"{collectionLink}:{id}";
if (Cache.TryGetValue(cacheKey, out cacheEntry))
{
var ac = new AccessCondition { Condition = cacheEntry.ETag, Type = AccessConditionType.IfNoneMatch };
var response = await client.ReadDocumentAsync(cacheEntry.SelfLink, new RequestOptions { AccessCondition = ac });
if (response.StatusCode == HttpStatusCode.NotModified)
{
return cacheEntry;
}
cacheEntry = response.Resource;
}
else
{
cacheEntry = (from f in client.CreateDocumentQuery(collectionLink, new FeedOptions { EnableCrossPartitionQuery = true })
where f.Id == id
select f).AsEnumerable().FirstOrDefault();
}
Cache.Set(cacheKey, cacheEntry);
return cacheEntry;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment