Newsbot.Portal/Newsbot.Collector.Client/SourcesClient.cs

59 lines
1.5 KiB
C#

using Newsbot.Collector.Client.Domain.Dto;
using Newtonsoft.Json;
namespace Newsbot.Collector.Client;
public interface ISourcesClient
{
public Task<SourcesDto> GetAsync(Guid id);
public SourcesDto Get(Guid id);
public Task<List<SourcesDto>> ListAsync();
public List<SourcesDto> List();
}
public class SourcesClient : ISourcesClient
{
private HttpClient HttpClient { get; set; }
private string InstanceUri { get; set; }
public SourcesClient(HttpClient httpClient, string instanceUri)
{
HttpClient = httpClient;
InstanceUri = instanceUri;
}
public async Task<SourcesDto> GetAsync(Guid id)
{
var res = await HttpClient.GetAsync(new Uri($"{InstanceUri}/api/sources/{id}"));
var content = await res.Content.ReadAsStringAsync();
var payload = JsonConvert.DeserializeObject<SourcesDto>(content);
payload ??= new SourcesDto();
return payload;
}
public SourcesDto Get(Guid id)
{
var res = GetAsync(id);
res.Wait();
return res.Result;
}
public async Task<List<SourcesDto>> ListAsync()
{
var res = await HttpClient.GetAsync(new Uri($"{InstanceUri}/api/sources"));
var content = await res.Content.ReadAsStringAsync();
var payload = JsonConvert.DeserializeObject<List<SourcesDto>>(content);
payload ??= new List<SourcesDto>();
return payload;
}
public List<SourcesDto> List()
{
var res = ListAsync();
res.Wait();
return res.Result;
}
}