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