CSharp · Console
using System;
using Flurl;
using Flurl.Http;
using Polly;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace APIProxy
{
public class SearchRankingAPIProxy
{
private string _apiBaseUrl;
public SearchRankingAPIProxy(string apiBaseUrl)
{
_apiBaseUrl = apiBaseUrl;
}
public async Task<IEnumerable<dynamic>> GetAllRankingResults(string searchTerm)
{
return await Policy
.Handle<FlurlHttpException>(IsWorthRetrying)
.WaitAndRetryAsync(ExponentialBackoff())
.ExecuteAsync(() => $"{_apiBaseUrl}/GetAllSearchRankings"
.SetQueryParam("searchTerm", searchTerm)
.GetJsonAsync<IEnumerable<dynamic>>());
}
private bool IsWorthRetrying(FlurlHttpException ex)
{
switch ((int)ex.Call.Response.StatusCode)
{
case 408:
case 500:
case 502:
case 504:
return true;
default:
return false;
}
}
private IEnumerable<TimeSpan> ExponentialBackoff()
{
return new[]{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(3),
TimeSpan.FromSeconds(5)
};
}
}
}