Created
February 23, 2017 01:41
-
-
Save dcomartin/2a0e0378d847360001442c20c12c6dbc 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
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