private bool _TryGetFromCache(string cacheKey, out GetDriveItemsResponse cachedResponse) { var entry = _itemsCache.FirstOrDefault(i => i.Key == cacheKey); bool found = false; if (entry != null) { if ((DateTime.Now - entry.Created).TotalSeconds > MaxCacheAgeSeconds) { _itemsCache.Remove(entry); cachedResponse = default; } else { entry.LastUsed = DateTime.Now; cachedResponse = entry.Value; found = true; } } else { cachedResponse = default; } return(found); }
public async Task <GetDriveItemsResponse> GetDriveItemsAsync(GetDriveItemsRequest request) { if (_TryGetFromCache(request.GetCacheKey(), out GetDriveItemsResponse cachedResponse)) { return(cachedResponse); } else { if (_TryGetRequestUrlWithPaging(request, out string requestUrl)) { (bool tokenSuccess, string token) = await _TryGetTokenAsync(); if (tokenSuccess) { _http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); string responseStr = await _http.GetStringAsync(requestUrl); var graphResponse = SimpleJson.SimpleJson.DeserializeObject <GraphResponse <DriveItem[]> >(responseStr, new SimpleJson.DataContractJsonSerializerStrategy()); var response = new GetDriveItemsResponse(graphResponse.Value, _GetSkipToken(graphResponse.NextLink)); _AddToCache(request, response); return(response); } } return(null); } }
private void _AddToCache(GetDriveItemsRequest request, GetDriveItemsResponse response) { if (!_TryGetFromCache(request.GetCacheKey(), out GetDriveItemsResponse cachedResponse)) { if (_itemsCache.Count > CacheLimit) { var prune = _itemsCache.OrderBy(c => c.LastUsed).First(); _itemsCache.Remove(prune); } _itemsCache.AddFirst(new LRUCacheEntry <GetDriveItemsResponse>() { Key = request.GetCacheKey(), Value = response, LastUsed = DateTime.Now, Created = DateTime.Now }); } }