chore: refactoring some code to introduce a common base class for all api classes

This commit is contained in:
Matthias Langhard
2021-05-21 22:13:04 +02:00
parent ac20e2e1d4
commit 89e7ce8449
34 changed files with 721 additions and 551 deletions

80
src/Shared/BaseApi.cs Normal file
View File

@@ -0,0 +1,80 @@
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Novaloop.PaymoApi.Extensions;
namespace Novaloop.PaymoApi.Shared
{
public class BaseApi<TReturnType, TCreatType> : IBaseApi<TReturnType, TCreatType>
{
public string ResourceUri { get; set; }
private readonly ApiOptions _options;
private readonly HttpClient _client;
public BaseApi(ApiClient apiClient, IOptions<ApiOptions> options)
{
_options = options.Value;
_client = apiClient.Client;
}
/// <summary>
/// Receive all entities
/// </summary>
public async Task<TReturnType> GetAll()
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.GetAsync($"api/{ResourceUri}");
await response.ThrowExceptionWithDetailsIfUnsuccessful();
return await response.Content.ReadAsAsync<TReturnType>();
}
/// <summary>
/// Retrieve an existing entity
/// </summary>
/// <param name="entityId">id of the entity</param>
/// <returns></returns>
public async Task<TReturnType> Get(int entityId)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.GetAsync($"api/{ResourceUri}/{entityId}");
await response.ThrowExceptionWithDetailsIfUnsuccessful();
return await response.Content.ReadAsAsync<TReturnType>();
}
/// <summary>
/// Create a new entity
/// </summary>
public async Task<TReturnType> Create(TCreatType entity)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.PostAsJsonAsync($"api/{ResourceUri}", entity);
await response.ThrowExceptionWithDetailsIfUnsuccessful();
return await response.Content.ReadAsAsync<TReturnType>();
}
/// <summary>
/// Delete an entity
/// </summary>
/// <param name="entityId">id of the entity</param>
/// <returns></returns>
public async Task Delete(int entityId)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.DeleteAsync($"api/{ResourceUri}/{entityId}");
await response.ThrowExceptionWithDetailsIfUnsuccessful();
}
/// <summary>
/// Update an entity
/// </summary>
/// <param name="entity">entity information to update the entity with</param>
/// <param name="id">id of the entity to update</param>
/// <returns></returns>
public async Task Update(TCreatType entity, int id)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.PutAsJsonAsync($"api/{ResourceUri}/{id}", entity);
await response.ThrowExceptionWithDetailsIfUnsuccessful();
}
}
}