YPS-Beer/backend/YPS.Beer/Services/PunkService.cs
2023-12-07 00:20:59 +00:00

47 lines
1.1 KiB
C#

namespace YPS.Beer.Services;
public class PunkService : IPunkService
{
private readonly HttpClient _httpClient;
private const string BaseUrl = "https://api.punkapi.com/v2/";
public PunkService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<Models.Beer?> GetBeer(int id)
{
var beer = await _httpClient.GetFromJsonAsync<Models.Beer[]>($"{BaseUrl}beers/{id}");
return beer?.SingleOrDefault();
}
public async Task<IEnumerable<Models.Beer>> GetBeers(params int[] ids)
{
var beers = new List<Models.Beer>();
foreach (var id in ids)
{
var beer = await GetBeer(id);
if (beer is not null)
beers.Add(beer);
}
return beers;
}
public async Task<IEnumerable<Models.Beer>> FindBeers(string search)
{
search = search.Replace(' ', '_');
var beers = await _httpClient.GetFromJsonAsync<Models.Beer[]>($"{BaseUrl}beers?beer_name={search}");
if (beers is null)
throw new Exception();
return beers;
}
}