Last active
August 24, 2020 12:46
-
-
Save LauraKokkarinen/d08ee78b9135dd12d11f77995f692498 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.Collections.Generic; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
namespace AzureFunctionsDependencyInjection.Services | |
{ | |
public class DataService : IDataService | |
{ | |
private readonly IBlobService _blobCache; | |
private const string CacheKeyData = "CACHE_KEY_DATA"; | |
public DataService(IBlobService blobCache) | |
{ | |
_blobCache = blobCache; | |
} | |
public async Task<IEnumerable<JToken>> GetDataAsync() | |
{ | |
return await GetCachedDataAsync() ?? await GetAndCacheDataAsync(); | |
} | |
private async Task<IEnumerable<JToken>> GetCachedDataAsync() | |
{ | |
string content = await _blobCache.GetBlobContentAsync(CacheKeyData); | |
return content != null ? (IEnumerable<JToken>)JsonConvert.DeserializeObject(content) : null; | |
} | |
public async Task<IEnumerable<JToken>> GetAndCacheDataAsync() | |
{ | |
var data = new List<JToken>(); // Get your data from the actual data source here | |
await CacheData(data); | |
return data; | |
} | |
private async Task CacheData(IEnumerable<JToken> data) | |
{ | |
await _blobCache.SetBlobContentAsync(CacheKeyData, JsonConvert.SerializeObject(data)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment