Exemple #1
0
        public async Task <IEnumerable <IHackerNewsArticle> > SearchTopStoriesAsync(string searchTerm)
        {
            // TODO: This could be more elegant (rather than returning nothing return something meaningful)
            if (searchTerm.Length > 50)
            {
                return(null);
            }

            // Sanitize input
            searchTerm = HttpUtility.HtmlEncode(searchTerm);

            var cacheKey = "HackerNewsServiceCaching.SearchTopStoriesAsync." + searchTerm.ToLower();

            if (_memoryCache.TryGetValue <IEnumerable <IHackerNewsArticle> >(cacheKey, out var storyTask))
            {
                return(storyTask);
            }
            else
            {
                var response = await this.GetAllTopStoriesAsync();

                if (response.Count() > 0)
                {
                    var topStories   = response.ToList();
                    var searchResult = topStories.Where(s => s.Title.Contains(searchTerm, StringComparison.OrdinalIgnoreCase));
                    return(searchResult);
                }
                else
                {
                    var topSearched = await _innerHackerNewsService.SearchTopStoriesAsync(searchTerm);

                    _memoryCache.Set(cacheKey, topSearched, TimeSpan.FromMinutes(10));
                    return(topSearched);
                }
            }
        }