Example #1
0
        public async Task <ActionResult <CharacterAnalysis> > GetCharacters(
            [FromRoute(Name = "leagueName")] string _leagueName,
            [FromQuery] GetCharactersConfig config
            )
        {
            config.Normalized();
            string leagueName;

            if (_leagueName == DEFAULT_LEAGUE_NAME)
            {
                PoeLeagueModel defaultLeague = await leagueService
                                               .GetDefaultLeagueQuery()
                                               .Select(x => new PoeLeagueModel {
                    LeagueId = x.LeagueId
                })
                                               .SingleOrDefaultAsync();

                if (defaultLeague != null)
                {
                    leagueName = defaultLeague.LeagueId;
                }
                else
                {
                    leagueName = _leagueName;
                }
            }
            else
            {
                leagueName = _leagueName;
            }
            var cacheKey      = $"{CHARACTERS_CACHE_PREFIX}:{leagueName}:{config.GetCacheKey()}";
            var encodedResult = await distributedCache.GetAsync(cacheKey);

            if (encodedResult != null)
            {
                var jsonStr = System.Text.Encoding.UTF8.GetString(encodedResult);
                var result  = JsonSerializer.Deserialize <CharacterAnalysis>(jsonStr);
                Response.Headers.Add("Cache-Control", "public, max-age=60");
                return(result);
            }
            else
            {
                var result = await leagueService.GetCharactersByAnalysis(leagueName, config);

                if (result.Total == 0)
                {
                    return(NotFound());
                }
                else
                {
                    int expirMulti = (int)(result.Total / 1000);
                    expirMulti = expirMulti < 1 ? 1 : expirMulti;
                    expirMulti = expirMulti >= 2 ? 2 : expirMulti;
                    var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(result);
                    var options   = new DistributedCacheEntryOptions()
                                    .SetSlidingExpiration(TimeSpan.FromMinutes(3 * expirMulti))
                                    .SetAbsoluteExpiration(DateTime.Now.AddHours(1 * expirMulti));
                    await distributedCache.SetAsync(cacheKey, jsonBytes, options);

                    Response.Headers.Add("Cache-Control", "public, max-age=180");
                    return(result);
                }
            }
        }