Newsbot.Portal/Newsbot.Collector.Client/ArticlesClient.cs

74 lines
2.3 KiB
C#

using Newsbot.Collector.Client.Domain.Dto;
using Newtonsoft.Json;
namespace Newsbot.Collector.Client;
public interface IArticlesClient
{
public Task<ArticlesDto> GetArticleAsync(Guid id);
public ArticlesDto GetArticle(Guid id);
public Task<List<ArticlesDto>> ListArticlesAsync();
public List<ArticlesDto> ListArticles();
public Task<List<ArticlesDto>> ListBySourceAsync(Guid sourceId);
public List<ArticlesDto> ListBySource(Guid sourceId);
}
public class ArticlesClient : IArticlesClient
{
private HttpClient Client { get; set; }
private string InstanceUri { get; set; }
public ArticlesClient(HttpClient client, string instanceUri)
{
Client = client;
InstanceUri = instanceUri;
}
public async Task<ArticlesDto> GetArticleAsync(Guid id)
{
var res = await Client.GetAsync(new Uri($"{InstanceUri}/api/articles/{id}"));
var content = await res.Content.ReadAsStringAsync();
var payload = JsonConvert.DeserializeObject<ArticlesDto>(content);
payload ??= new ArticlesDto();
return payload;
}
public ArticlesDto GetArticle(Guid id)
{
var res = GetArticleAsync(id);
res.Wait();
return res.Result;
}
public async Task<List<ArticlesDto>> ListArticlesAsync()
{
var res = await Client.GetAsync(new Uri($"{InstanceUri}/api/articles"));
var content = await res.Content.ReadAsStringAsync();
var payload = JsonConvert.DeserializeObject<List<ArticlesDto>>(content);
payload ??= new List<ArticlesDto>();
return payload;
}
public List<ArticlesDto> ListArticles()
{
var res = ListArticlesAsync();
res.Wait();
return res.Result;
}
public async Task<List<ArticlesDto>> ListBySourceAsync(Guid sourceId)
{
var res = await Client.GetAsync(new Uri($"{InstanceUri}/api/articles/by/{sourceId}"));
var content = await res.Content.ReadAsStringAsync();
var payload = JsonConvert.DeserializeObject<List<ArticlesDto>>(content);
payload ??= new List<ArticlesDto>();
return payload;
}
public List<ArticlesDto> ListBySource(Guid id)
{
var res = ListBySourceAsync(id);
res.Wait();
return res.Result;
}
}